Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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.

share|improve this answer
    
could you explain why it works without [[ ... ]]? –  Majid Azimi Feb 19 '12 at 18:14
    
sure, I edit the answer. –  jfgagne Feb 19 '12 at 18:27
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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