Red Hat Linux 7 Unleashed

Red Hat Linux 7 Unleashed

By William Ball

Positional Parameters

It is possible to write a shell script that takes a number of parameters at the time you invoke it from the command line or from another shell script. These options are supplied to the shell program by Linux as positional parameters, which have special names provided by the system. The first parameter is stored in a variable called 1 (number 1) and can be accessed by using $1 within the program. The second parameter is stored in a variable called 2 and can be accessed by using $2 within the program, and so on. One or more of the higher numbered positional parameters can be omitted while you're invoking a shell program.

For example, if a shell program mypgm expects two parameters--such as a first name and a last name--you can invoke the shell program with only one parameter, the first name. However, you cannot invoke it with only the second parameter, the last name.

Here's a shell program called mypgm1, which takes only one parameter (a name) and displays it on the screen:

#!/bin/sh
#Name display program
if [ $# -eq 0 ]
then
   echo "Name not provided"
else
   echo "Your name is "$1
fi

If you execute mypgm1 in pdksh and bash as follows


   # . mypgm1

you get the following output:

Name not provided

However, if you execute mypgm1 as follows


   # . mypgm1 Sanjiv

you get the following output:

Your name is Sanjiv

The shell program mypgm1 also illustrates another aspect of shell programming: the built-in variables. In mypgm1, the variable $# is a built-in variable and provides the number of positional parameters passed to the shell program.

Share ThisShare This

Informit Network