z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Using positional parameters — the $N construct

z/OS UNIX System Services User's Guide
SA23-2279-00

The sample shell script discussed previously in this topic compiled and link-edited a program stored in a collection of source modules. This information discusses a shell script that can compile and link-edit a C program stored in any file.

To create such a script, you need to be familiar with the idea of positional parameters. When the shell encounters a $N construct formed by a $ followed by a single digit, it replaces the construct with a value taken from the command line that started the shell script.
  • $1 refers to the first string after the name of the script file on the command line
  • $2 refers to the second string, and so on.
As a simple example, consider a shell script named echoit consisting only of the command:
echo $1
Suppose we run the command:
echoit hello
The shell reads the shell script from echoit and tries to run the command it contains. When the shell sees the $1 construct in the echo command, it goes back to the command line and obtains the first string following the name of the shell script on the command line. The shell replaces the $1 with this string, so the echo command becomes:
echo hello
The shell then runs this command.

A construct like $1 is called a positional parameter. Parameters in a shell script are replaced with strings from the command line when the script is run. The strings on the command line are called positional parameter values or command-line arguments.

If you enter:
echoit Hello there
the string Hello is considered parameter value $1 and the string there is $2. Of course, the shell script is only:
echo $1
so the echo command displays only the Hello.
Positional parameters that include a blank can be enclosed in quotation marks (single or double). For example:
echoit "Hello there"
echoes the two words instead of just one, because the two words are handled as one parameter.
Returning to a compile and link example, a programmer could write a more general shell script as:
c89 -c $1.c
c89 -o $1 $1.o
If this shell script were named clink, the command:
clink prog
would compile and link prog.c, producing an executable file named prog in the working directory. In the same way, the command:
clink dir/prog2
would compile and link dir/prog2.c. The shell script compiles and links a C program stored in a single file.
As another example of a shell script containing a positional parameter, suppose that the file lookup contains:
grep $1 address
(where address is a file containing names, addresses, and other useful information). The command:
lookup Smith
displays address information about anyone in the file named Smith.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014