NH. NH. - 1 year ago 76
Bash Question

Why does test say unexpected parenthesis?

I have an

line in my shell script that looks like this:

if [ 0 -lt 2 -o (0 -gt 3 ) ]

and this gives the error:

line 3: syntax error near unexpected token \`('

So I looked at
man test
to be sure that parens were supported, and sure enough, very near the top of the man page, they are! What gives!?

The example above doesn't exactly match the code because I was trying to clean it to prove a point, but this is my repo if you needed context.

EDIT: changed the if line to match the error.

Answer Source

The parenthesis are passed to the test command as arguments. The [ ... ] expression is just another way to type the test command. The only difference is that the last argument for the [ command must be ].

So you should escape the parenthesis just as any other arguments you pass to a command to avoid the shell interpretation:

if [ \( $# -lt 2 \) -o \( $# -gt 3 \) ]

Alternatively, use single quotes:

if [ '(' $# -lt 2 ')' -o '(' $# -gt 3 ')' ]

From the info page:

          test EXPR

     Evaluate a conditional express ion EXPR and return a status of 0
     (true) or 1 (false).  Each operator and operand must be a separate

By the way, the expression could be rewritten as follows:

if builtin test \( $# -lt 2 \) -o \( $# -gt 3 \)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download