Reputation: 3006
What is wrong with the below script?
if [ $# -eq 0 -o $1 = "-h" -o $1 = "--help" ]; then ## line no: 11
echo $usage
exit 0;
fi
If run without any arguments, it gives the below error
% ./test.sh
./test.sh: line 11: [: too many arguments
Upvotes: 0
Views: 37
Reputation: 55469
Rather than using -o
you can use ||
to do short-circuit evaluation, i.e., if a condition is true the subsequent conditions won't be evaluated.
if [ -z "$1" ] || [ "$1" = '-h' ] || [ "$1" = '--help' ]; then
echo "$usage"
exit 0
fi
If you're only running this script in bash you can do use this more compact syntax:
if [[ -z "$1" || "$1" = '-h' || "$1" = '--help' ]]; then
echo "$usage"
exit 0
fi
but that may not work in other shells.
Note that I've also quoted the argument to echo
. In general, you should quote parameters unless you explicitly want word splitting. I guess I ought to mention that printf
is more robust than echo
, but echo
is ok for fixed strings.
Upvotes: 2
Reputation: 101
You have to quote $1
because if it's empty and not quoted, it will be replaced by literally nothing instead of and empty string
if [ $# -eq 0 -o "$1" = "-h" -o "$1" = "--help" ]; then
echo $usage
exit 0;
fi
Upvotes: 0