More on positional parameters

When a command is executed, the Unix system provides a copy the command's name and any arguments specified on the command line to the command. If the command is shell script or another copy of the command shell, this information can be access using the command line positional parameters.

The parameters are numbered from 0 to n. I've tried up to 3000 arguments on a Suse Linux system and had no problems.

The positional parameter $0 represents the command's name. With linking, it is posible to assign more than one name to a program. The $0 allows the program to determine its own name and act accordingly.

To access each argument after the commands name, use the $ dereference and the position, $1, $2, etc. For the 1st nine positions, this is straight forward. However, you must use the brace syntax to indicate that the multi-digit value is a single parameter position.

#( Using the editor of your choice, create a file called parms and enter the following shell program. )

#!/bin/bash

#( Display count of command line arguments )
echo "My name is : $0"

echo "parameter count $#"

#( Display the whole list )
echo "All : $*"

if [ $# -gt 10 ]
then
  #( Print specific arguments from the list )
  echo $1 $11 ${11}
fi

#( Save the file )

#( Set your file's execute permissions and run )
chmod 700 parms

./parms one two three four five six seven eight nine ten eleven twelve

Your program will display its name, the count of arguments on the command line, and the whole argument list.

Remember, you can print the command line argument count with $# and the whole argument list with either $* or $@.

The program will then print three of the command line arguments. You will notice that the final echo prints three strings, the 1st argument, the 1st argument again with the digit 1 concatentated to it. And the finally the 11th argument. The braces are required around the parameter index value if it is more than 1 digit long.

In the original Bourne shell you could only reference the 1st 9 parameter arguments without calling the shift command. shift shifts the contents of the 2nd positional argument into the 1st position, the 3rd into the 2nd, etc. However, the original 1st value is lost. So, some careful planning was necessary when working with long parameter lists.

We will revisit the shift when we look at shell programming in detail.


Next we will look at the history mechanism which allows you to recall and run previously entered commands.

The history mechanism