Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use not (!) in parentheses in Bash?

I want to do something like this:

if [ (! true) -o true ]
then
    echo "Success!"
else
    echo "Fail!"
fi

But it throws an error (-bash: syntax error near unexpected token '!')

Is it possible to do anything like this?

like image 878
Tyilo Avatar asked May 28 '11 18:05

Tyilo


1 Answers

The problem here is that [ is a simple buildtin command in bash (another way to write test), which can only interpret whatever parameters it gets, while ( is an operator character. The parsing of operators comes before command execution.

To use ( and ) with [, you have to quote them:

if [ \( ! true \) -o true ]
then
    echo "Success!"
else
    echo "Fail!"
fi

or

if [ '(' ! true ')' -o true ]
then
    echo "Success!"
else
    echo "Fail!"
fi

The [[ ... ]] construct is a special syntactic construct which does not have the syntactic limitations of usual commands, since it works on another level. Thus here you don't need to quote your parentheses, like Ignacio said. (Also, you have to use the && and || instead of -a and -o here.)

like image 197
Paŭlo Ebermann Avatar answered Oct 22 '22 16:10

Paŭlo Ebermann