Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does test say unexpected parenthesis?

Tags:

bash

shell

sh

I have an if 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.

like image 500
NH. Avatar asked Dec 19 '22 11:12

NH.


1 Answers

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'
`['
          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
     argument.

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

if builtin test \( $# -lt 2 \) -o \( $# -gt 3 \)
like image 129
Ruslan Osmanov Avatar answered Jan 12 '23 11:01

Ruslan Osmanov