April 09, 2012, 10:19 AM —
Two of the best reasons for building shell scripts on Unix systems are 1) to repeat complex sets of instructions without having to rediscover or even retype the commands, and 2) to repeat complex sets of instructions against any number of targets -- thus the need to supply arguments to your scripts.
Arguments provided to shell scripts, such as when you type "doit this that" are available for testing, manipulation and action within your scripts. The arguments themselves are available as $1, $2, $3 and so on -- or you can reference all of them at once using $@. The $0 argument displays the name of your script itself while $# represents the number of arguments provided to the script. The following script segment, for example, will add a message to a log file if the script is run without the correct number of arguments:
#!/bin/bash
if [ $# != 3 ]; then
echo "$0: wrong number of arguments provided" >> $0.log
fi
It's always a good idea to verify that arguments have been provided before you allow your script to work with them, though you can decide whether to abort if too many arguments are provided or just ignore the extras.


















