Home » 2014 » April » 24 » Addition of two numbers using shell scripting in UNIX

8:18 PM
Addition of two numbers using shell scripting in UNIX

Hello all

We will see a very simple example to add two numbers using shell scripting. Here we will accept two numbers from the user and display the result on the console

We will create a simple script with name test.sh and type below lines in it.


echo "Enter first number:"

read a

echo "Enter second number:"

read b


echo "Result is:"

echo $sum

Now we will try to understand the above script.

First line is the Shebang line which is telling what shell we r using. Currently it is Korn shell, that is why it is #!/usr/bin/ksh . Now we are reading two numbers a and b from user prompt using read command. The vlaue read from user are stored into a and b respectively.

The vlaue of any variable can be accessed using $<varname>. So the summation is done using $(($a+$b))  and the value is stored into sum. Finally the result vlaue is displayed as $sum

To execute this script , you first need to the set the execute permission for this script because by default the user does not have execute permission on the file.

 Promt:>ll test.sh
-rw-rw-r-- 1 user1 qxbmw 43 2014-04-24 16:16 test.sh
So the set execute execute permission, we do:

chmod u+x test.sh

The above command adds the execute permission to the user.

 Prompt:>ll test.sh
-rwxrw-r-- 1 user1 qxbmw 43 2014-04-24 16:16 test.sh
Now we can execute the script

Next we will see another method where we will be passing the two numbers as arguments to the script.

Create a file with test2.sh and put below lines:

       c=$(($1 + $2))
       echo $c;


To execute this script we will send the two numbers as argument. So, we will execute like this:

./test2.sh 34 56

The result will be : 90

Lets see another example which will help us understand more on shell scripting.

2. Accept one more positional parameters and and verify the parameter supplied and depending on several conditions proceed further or exit.

For example, we will accept one file name as first argument to the script and then will do following things:

  • If no arguments were supplied, the program should exit with following error message:

         No arguments were given. At least one argument needed.

         Usage: script-name filename

  • When one argument is given, it should check if the file actually exists. If yes, it should print "File exists" and the type of file , if no, the program will exit saying file does not exist.

See below program:


if [[ $# -eq 0 ]]; then
  print "No argument was supplied!!";
  print "Usage: $0 filename" ;
  exit 32;
  if [[ -e $1 ]]; then
   print "The file exists, processing will continue";
   filetype=$(file -b $1);
             if [[ $filetype = "ASCII text" ]]; then
                print "The file is of type $filetype "
                print "The file $1 is not of type ASCII, the program will exit";
                exit 34;

      print "No such file exists, please confirm the file name";


Here, we have to remember below things:

Prompt:>command arg1 arg2 arg3 .....
  • $# --> refers to the numbers of arguments given.
  • $0 --> refers to the scriopt or the command itself.
  • $1 --> refers to the first argument given to the script.
  • $2 --> refers to the second argument given to the script  and so on..
  • So, we check in first if condition that the no. of arguments given is zero or more. If its zero, we print "No argument given" and script usage.
  • Else, we check if the file exists using "test -e $1" or [[ -e $1 ]] . If the condition becomes true, we print "File exists and processing will continue"
  • Then, we store the type of file using the command "file -b $1" into a variable filetype and print it.
  • We compare the filetype variable with "ASCII  text". If it succeeds, the program will print "The file is of type $fileype" or else it will say "The file is not ASCII, the program will exit"
  1. First run:

Prompt:> ./checkFile1.sh
No argument was supplied!!
Usage: ./checkFile1.sh filename

2. Second run:

Prompt:> ./checkFile1.sh someAsciiFile.txt
The file exists, processing will continue
The file is of type ASCII text


3. Third Run:

Prompt:> ./checkFile.sh someAsciiFile.txt
No such file exists, please check the file name

The program will exit


**************************Case syntax *************************

We will see a simple example on this and try to understand the "case syntax".


items= (cofee tea limejuice banana-sake);
case $urchoice in
    print "The choice is one";
    print "You get ${items[0]}!!";;
    print "The choice is two";
    print "You get ${items[1]}!!";;
    print "The choice is three";
    print "You get ${items[2]}!!";;
    print "The choice is four";
    print "You get ${items[3]}!!";;
    print "Give proper choice!!";;


So the syntax is:

case expression in






print "Give poper choice!!";;


*********************For loop syntax***************************

Lets see some examples of basic for loops in shell scripting:

The syntax is:

for variable in range;


#some coding....


The range could be a set of strings, a set of numbers, commands etc. The for loop will traverse the range and for that range it will perform steps written between do and done

Example 1:


for name in shanky priyanka thiru;
    print $name;

  • The above code on execution will print:


Example 2:

server1:/home/user1/test:>cat forloop2.sh

for i in {1..10};
print $i;

The above program will print all numbers given in the range as {n1..n2}.

Example 3:


for i in `ls -aF`;

print "Files are:$i";


The above program wil run the command in loop for all listed files in the current directory. Here we are specifying the commands ls -aF as the range for for loop.

Note: `ls -aF` us same as $(ls -aF)

***********************************While LOOP Syntax****************************************8

while [[ $i -lt 10 ]];     do
    echo $i ;
    (( i += 1 ));


The output will be:

shanky@linux-host:/home/shanky:> ./whileLoop.ksh

 List factors of a number using while loop

Here is another example of while loop to list all the factors of a number.

Logic: Use a while loop to find all numbers till that number that can divide the number. So we shall start from 1 and navigate till the entered number and check which number can divide the number leaving a remainder as Zero.

Remainder can be evaluated as below:

rem=`expr $num % $i`;     #rem stores the remainder of division of number by i

if [[ $# -eq 0 ]]; then
        echo "Usage: $0 <number>";
        exit 0;
echo "Factors of $1 are:"

while [[ $i -le $1 ]]; do
        rem=`expr $1 % $i`;     #rem stores the remainder of division of number by i
        if [[ $rem -eq 0 ]]; then
                echo -n "$i "   #if remainder is zero, the i is a factor
        i=$(($i+1)); #increment i by 1
echo ""
echo ""



[[email protected] tmp]# ./factor.sh 643
Factors of 643 are:
1 643

[[email protected] tmp]# ./factor.sh 456
Factors of 456 are:
1 2 3 4 6 8 12 19 24 38 57 76 114 152 228 456





Category: Open System-Linux | Views: 2552 | Added by: ved | Tags: add two numbers in linux, script to add two numbers, how to perform addition of two numb, How to add two numbers in shell scr | Rating: 5.0/1

Related blogs

You may also like to see:

[2014-03-25][Open System-Linux]
Create a new user in Linux system: useradd
[2014-09-13][Open System-Linux]
md5sum: calculate and check md5 message digest of a file in Linux
[2014-03-17][Open System-Linux]
AWK command for scanning and analysing a large file in Linux
[2014-11-25][Open System-Linux]
DMESG command in Linux : to display or control kernel ring buffer
[2014-02-27][Open System-Linux]
RSYNC : A command in linux to copy files remotely. Faster and more flexible than rcp

Total comments: 2
1 Piyu • 7:59 PM, 2014-05-13
wow. great script for begineers.
2 shanky • 5:15 PM, 2014-09-07
To coment a line in shell script:

# one line comment

To make a multiline comment in Linux shell scripts:

: '
This is a