Shell Script Tutorial

Parsing Argument

Arguments and Other Special Variables

Arguments are the values you pass to a shell script. Each value on the command line after the name of the script will be assigned to the special variables $1, $2, $3, and so on. The name of the currently running script is stored in the $0 variable.

Here are some other special variables you will find useful in script writing:

$# The number of arguments

$* The entire argument string

$? The return code from the last command issued

So let's try some examples working with arguments and other special variables. Create an executable script called 'argument.sh' containing these lines:

#!/bin/bash if [ $# -ne 1 ]; then echo "Usage: argument.sh arg1 arg2" exit 1 fi echo "My script is $0" echo "First arg is: $1" echo "Second arg is: $2" echo "I got a total of $# arguments." echo "The full argument string was: $*"

Now if you run this script, here's what you'll see:

[root@~]# ./argument.sh alan is pig

My script is argument.sh
First arg is: alan
Second arg is: is
I got a total of 3 arguments.
The full argument string was: alan is pig



Server is hosted by Alanstudio
Linux Operating System

Recommend screen resolution 1024 x 768 / IE / FireFox
Alan Studio © 2007 by Alan Cheung Hin Lun. All rights reserved.