0

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
1
  • 1
    You should quote your variables, particularly $1 in this case. May I recommend shellcheck.net ? Commented Feb 2, 2015 at 7:14

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.