Check for number of arguments in bash

# Check for proper number of command line args.

EXPECTED_ARGS=1
E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: `basename $0` {arg}"
  exit $E_BADARGS
fi

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

bash args

An easier way would be via parameter substitution:

: ${1?"Usage: $0 ARGUMENT"}

If parameter set, use it, else print error message.

False?

Wouldn't that cause problems if the arguments passed were 0 and/or "" ?

Your check for expected Bash script Args

Sandip,

your check doesn't seem to allow a * wildcard to pass the check as an argument - it simply seems not to be counted. Why is that? My script must be able to accept this.

Any ideas, or a possible fix?

Cheers,
J.

bash globbing

That is due to bash globbing.

Try prefixing the * with \ like \* or,

`set -f` to disable globbing and then run the script.

Post new comment

  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.
Comment