Skip to content
Advertisement

Bash script: too many arguments in [ test ]

I have the bash script below:

#!/bin/bash
#
[ $# -eq 1 -a $1 = "--help" -o $# -eq 0 ] && {
  echo Help will come here
}

When I run it:

$ ./script 
./script: line 3: [: too many arguments
$ ./script --help
Help will come here

As you can see, when I don’t pass parameters ( $# -eq 0 ) it fails with “too many arguments”. So, I tested it directly in terminal:

$ a=1;b=2;c=3
$ [ $a -eq 1 -a $b -eq 2 -o $c -eq 3 ] && echo ok
ok
$ [ $a -eq 0 -a $b -eq 2 -o $c -eq 3 ] && echo ok
ok
$ [ $a -eq 0 -a $b -eq 0 -o $c -eq 3 ] && echo ok
ok
$ [ $a -eq 0 -a $b -eq 0 -o $c -eq 0 ] && echo ok
$ [ $a -eq 0 -a $b -eq 2 -o $c -eq 0 ] && echo ok
$ [ $a -eq 1 -a $b -eq 2 -o $c -eq 0 ] && echo ok
ok

So, if it works perfectly in terminal why doesn’t it work passing parameters?

Thanks,

Advertisement

Answer

Your entire expression can be simplified to:

function help () {
    printf "%sn" "help is on it's way."
}

[[ $# -eq 0 || "$*" = "--help" ]] && help ; echo "done." && exit 0 ;

This checks if the total sum of arguments is zero, or the argument(s) equals “–help”. If either of those two things are true then it proceeds to the help function, otherwise echo “done” and exit.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement