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.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

IT ManagementWhite Papers & Webcasts

See more White Papers | Webcasts

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question
randomness