2

I have a script:

#!/bin/bash

if [[ read -t 10 -sp "Enter Password: " passwd ]]; then
    echo -e "\nPassword: ${passwd}"
else
    echo -e "\nInput timed out" >&2
    exit 1
fi

exit 0

But it gives error:

./script.sh: line 3: conditional binary operator expected
./script.sh: line 3: syntax error near `-t'
./script.sh: line 3: `if [[ read -t 10 -sp "Enter Password: " passwd ]]; then'

What is wrong with my code?

4

You do not need the [[ ... ]]. Simply rewrite it as:

#!/bin/bash

if read -t 10 -sp "Enter Password: " passwd; then
  echo -e "\nPassword: ${passwd}"
else
  echo -e "\nInput timed out" >&2
  exit 1
fi

exit 0

or to be easier to read and/or shorter:

#!/bin/bash
read -t 10 -sp "Enter Password: " passwd || echo -e "\nInput timed out" >&2 && exit 1
echo -e "\nPassword: ${passwd}"
exit 0

Update:

To understand why it works without [[ ... ]], the bash man must be checked:

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, [...]

In this case, The if list is the read command. [ $? -eq 0 ] and test $? -eq 0 are also valid lists with specific exit status. [[ expression ]] (again according to bash's man) is also a valid list, but read -t 10 -sp "Enter Password: " passwd is not a valid expression. See the man to know what are valid expressions.

  • could you explain why it works without [[ ... ]]? – Majid Azimi Feb 19 '12 at 18:14
  • sure, I edit the answer. – jfg956 Feb 19 '12 at 18:27
2

You're using command inside the [[ ]] statement, which makes no sense. This operator should be used like test function for checking some condition.

It's better to run read command separately and check it's exit code then.

#!/bin/bash

read -t 10 -sp "Enter Password: " passwd

if [ $? -eq 0 ]; then
    echo -e "\nPassword: ${passwd}"
else
    echo -e "\nInput timed out" >&2
    exit 1
fi

exit 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.