Fun with shell $ arguments

By  

  Sign me up for ITworld's FREE daily newsletter!
Email: 
 

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.

Follow Sandra on Google+

Sandra Henry-Stocker has been administering Unix systems for more than 25 years. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She currently works for TeleCommunication Systems -- a company that builds innovative technologies to make critical connections happen -- where no one else necessarily shares any of her opinions. Send comments and suggestions to bugfarm@gmail.com.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Ask a Question