/ Linux

Shell Scripting - Arguments / Positional Parameters

In this series of Shell Scripting, today we discuss about command line arguments also know as positional parameters.

To handle options on the command line, we use a facility in the shell called positional parameters. Positional parameters are a series of special variables ($0 through $9) that contain the contents of the command line.

For Example:

[swapnil@googlinux.com]$ myprog.sh Swapnil Jain Indore

If myprog.sh is a shell script, we could read each item on the command line because the positional parameters contain the following:

  • $0 would contain "myprog.sh"
  • $1 would contain "Swapnil"
  • $2 would contain "Jain"
  • $3 would contain "Indore"

Here is a simple script you would like to try:


echo "Program Name is $0"
echo "First Name is $1"
echo "Last Name is $2"
echo "City is $3"


[swapnil@googlinux.com]$ ./myprog.sh Swapnil Jain Indore
Program Name is ./myprog.sh
First Name is Swapnil
Last Name is Jain
City is Indore
Improving your Script

You can further improve this script by using some help and error handling


if [ $# -lt 3 ];then
   echo "ERROR: minimum 3 paramerts required"
   echo "Example: myprog.sh fname lname city"
   echo "Program Name is $0"
   echo "First Name is $1"
   echo "Last Name is $2"
   echo "City is $3"
  • $# - contains the total number of parameters

You can play a lot with shell script, create simple programs to automate task. Stay tuned for more. Thats it for positional parameters.

Like it? Click here to Tweet your feedback