Special Shell Variables

For your convenience, the shell predefines several variables, some of which change as your script runs. Others are permanently set for the life of the script.

Checking the Number of Command-Line Arguments Given

When someone runs your script, it is always good to make sure that the user typed in the correct number of arguments on the command line. When your script is run, the shell sets $# to that number. You can check it by using the integer comparison operators already discussed.

If the script requires exactly three arguments, here’s how you could check that:

if [ "$#" -ne 3 ]
then
   echo "Usage: $0 filename username dirname" >&2
   exit 1
fi

You will normally perform this test before checking any of the command-line arguments. ...

Get Practical UNIX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.