Tyilo
Tyilo

Reputation: 30102

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?

Upvotes: 6

Views: 1755

Answers (2)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74760

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.)

Upvotes: 5

zwol
zwol

Reputation: 140659

You can't do that, but you can do this:

if [ ! true ] || [ true ]

As a general rule, never try to use the -a or -o options to [.

Upvotes: 3

Related Questions