Shell script to add two numbers using command line arguments
In shell script we can pass the arguments from command line.
In this tutorial, we will learn how to add two numbers using command line arguments.
Pass arguments from command line - shell script
To pass arguments from the command line, add the argument values after the file name while executing the script.
Like,
sh file_name.sh arg1 arg2
In script $1 will refer the value of agr1, and $2 will refer the value of arg2 and so on.
Algorithm
1. Pass the arguments while executing the script.
2. Get first arguments using $1 and second argument using $2.
3. Add $1 and $2 and display the result.
Add two variables using command line argument in shell script
#shell script to add two numbers #using command line arguments #$1 refers to the first argument #$2 refers the second argument and so on sum=$(($1 + $2)) echo "Sum = $sum"
Run the script
sh add.sh 10 20
Output
Sum = 30
sh add.sh 100 20
Output
Sum = 120
Useful Resources
To learn more shell script examples, you can visit the link