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.
[email@example.com]$ myprog.sh Swapnil Jain Indore
myprog.sh is a shell script, we could read each item on the command line because the positional parameters contain the following:
Here is a simple script you would like to try:
#!/bin/bash echo "Program Name is $0" echo "First Name is $1" echo "Last Name is $2" echo "City is $3"
[firstname.lastname@example.org]$ ./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
#!/bin/bash if [ $# -lt 3 ];then echo "ERROR: minimum 3 paramerts required" echo "Example: myprog.sh fname lname city" else echo "Program Name is $0" echo "First Name is $1" echo "Last Name is $2" echo "City is $3" fi
$#- 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