Shell Script - Passing Command line arguments

In this article, let us see how to get the command line arguments in the Shell Script program.

Consider the following Shell Script which does addition of two numbers using the constant values.

echo "Program to add two numbers"
a=1
b=2
sum=`expr $a + $b`
echo "Sum = ${sum}"

Now, let’s see how to get these two values from command line arguments and perform addition.

Consider the following Shell Script which gets the values from the command line arguments.

echo "Program to get the command line argument"

# Get the first argument
a=$1

# Get the second argument
b=$2
sum=`expr $a + $b`
echo "Sum of Argument = ${sum}"
 

Execute the above Shell Script as below,

$ sh CommandLineDemo.sh 1 2
Program to get the command line argument
Sum of Argument = 3

Here, we are executing the script with arguments passed as 1 and 2. These arguments can be accessed in the script using $1 and $2 and so on.

Note:
$0 - Returns the Shell Script file name. In our example, it is CommandLineDemo.sh

$# - Returns the number of Shell Script command line arguments. In our example, it is 2.

$* - Used to get all of the command line arguments.

Technology: 

Search