tags:

views:

63

answers:

3

Hello,

I'm not sure how to do an if with multiple tests in shell, I'm having trouble writing this script:

echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" && "$arg1" != "$arg3" ]
then 
    echo "Two of the provided args are equal."
    exit 3
elif [ $arg1 = $arg2 && $arg1 = $arg3 ]
then
  echo "All of the specified args are equal"
  exit 0
else
  echo "All of the specified args are different"
  exit 4 
fi

the problem is I get this error every time: ./compare.sh: [: missing `]' command not found Thank you!

+2  A: 

Change "[" to "[[" and "]" to "]]".

Ethan Post
Better yet, change '[' to 'test'
William Pursell
+2  A: 

Use double brackets...

if [[ expression ]]

Henryk Konsek
To note, this is a solution because the `[[` construct is built into the shell while `[` is another name for the `test` command and hence is subject to its syntax -- see `man test`
glenn jackman
Technically, `[` is a shell builtin, but `[[` is a shell keyword. That’s the difference.
jleedev
+5  A: 

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]

Also, you should always quote the variables, because [ gets confused when you leave off arguments.

jleedev
Henryk Konsek