Shell script command line arguments

In shell programming, command line arguments are saves to $0, $1, $2, $3, … $0 is always the file name of the shell script. $1 stores the first command line argument, $2 stores the second, $3 stores the third, and so forth. $# stores the total number of arguments that was passed from the command line excluding the $0

#!/bin/sh
arg0=$0
arg1=$1
arg2=$2
arg3=$3
numOfArgs=$#
echo number of arguments: $numOfArgs
echo argument 0 is the file name of the script: $arg0

if [ -z "$arg1" ]; then
	echo argument 1 is empty
else
	echo argument 1 is $arg1
fi


if [ -z "$arg2" ]; then
	echo argument 2 is empty
else
	echo argument 2 is $arg2
fi     


if [ -z "$arg3" ]; then
	echo argument 3 is empty
else
	echo argument 3 is $arg3
fi 

Assume the above script is in commandlineargs.sh, then if you issue the command ./commandlineargs.sh aa bb, it will print these

number of arguments: 2
argument 0 is the file name of the script: ./commandlineargs.sh
argument 1 is aa
argument 2 is bb
argument 3 is empty

Search within Codexpedia

Custom Search

Search the entire web

Custom Search