Difference between revisions of "How to use positional parameters"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
Line 32: Line 32:
 
~/scripts/adddomain cyberciti.biz '74.86.48.99' '2607:f0d0:1002:11::4'  
 
~/scripts/adddomain cyberciti.biz '74.86.48.99' '2607:f0d0:1002:11::4'  
 
/etc/init.d/named reload
 
/etc/init.d/named reload
/usr/rc.d/jail restart cyberciti.biz</source>
+
/usr/local/etc/rc.d/jail restart cyberciti.biz</source>
 
{| style="cellpadding="20" cellspacing="0" border="1"  width="100%"
 
{| style="cellpadding="20" cellspacing="0" border="1"  width="100%"
 
! style="background:#ffdead;"| Shell script name ($0)
 
! style="background:#ffdead;"| Shell script name ($0)
Line 58: Line 58:
 
|reload
 
|reload
 
|-
 
|-
|/usr/rc.d/jail  
+
|/usr/local/etc/rc.d/jail
 
|2
 
|2
 
|restart, and cyberciti.biz
 
|restart, and cyberciti.biz
 
|}
 
|}
 +
 
{{navigation
 
{{navigation
 
|previous=Shell command line parameters
 
|previous=Shell command line parameters
 
|next=Parameters Set by the Shell}}
 
|next=Parameters Set by the Shell}}

Revision as of 21:55, 19 October 2009

← Shell command line parametersHomeParameters Set by the Shell →

All command line parameters ( positional parameters ) are available via special shell variable $1, $2, $3,...,$9.

How Do I Access Command-Line Arguments

Create a simple shell script called cmdargs.sh:

#!/bin/bash
echo "The script name : $0"
echo "The value of the first argument to the script : $1"
echo "The value of the second argument to the script : $2"
echo "The value of the third argument to the script : $3"
echo "The number of arguments passed to the script : $#"
echo "The value of all command-line arguments (\$* version) : $*"
echo "The value of all command-line arguments (\$@ version) : $@"

Save and close the file. Rut it as follows:

chmod +x cmdargs.sh
./cmdargs.sh bmw ford toyota

Sample outputs:

The script name : ./cmdargs.sh
The value of the first argument to the script : bmw
The value of the second argument to the script : ford
The value of the third argument to the script : toyota
The number of arguments passed to the script : 3
The value of all command-line arguments : bmw ford toyota

Try the following examples:

ls /tmp
./math 10 + 2 
~/scripts/addzone cyberciti.com
~/scripts/adddomain cyberciti.biz '74.86.48.99' '2607:f0d0:1002:11::4' 
/etc/init.d/named reload
/usr/local/etc/rc.d/jail restart cyberciti.biz
Shell script name ($0) Total number of arguments ($#) Actual Command line argument ($1,..,$9)
ls 1 /tmp
./math 3 10, +, and 3
~/scripts/addzone 1 cyberciti.com
~/scripts/adddomain 3 cyberciti.biz, 74.86.48.99, and 2607:f0d0:1002:11::4
/etc/init.d/named reload 1 reload
/usr/local/etc/rc.d/jail 2 restart, and cyberciti.biz

← Shell command line parametersHomeParameters Set by the Shell →