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.

#!/usr/bin/ksh

echo "Enter first number:"

read a

echo "Enter second number:"

read b

sum=$(($a+$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:

       #!/usr/bin/ksh
       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:

#!/usr/bin/ksh

if [[ $# -eq 0 ]]; then
  print "No argument was supplied!!";
  print "Usage: $0 filename" ;
  exit 32;
else
  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 "
             else
                print "The file $1 is not of type ASCII, the program will exit";
                exit 34;
            fi

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

  fi
fi

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".

#!/usr/bin/ksh

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

esac

So the syntax is:

case expression in

case1)

command1;;

case2)

command2;;

*)

print "Give poper choice!!";;

esac

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

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

The syntax is:

for variable in range;

do

#some coding....

done

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:

#!/usr/bin/ksh

for name in shanky priyanka thiru;
do
    print $name;
done;

  • The above code on execution will print:

server1:/home/shanky/test:>./forloop.sh
shanky
priyanka
thiru


Example 2:

server1:/home/user1/test:>cat forloop2.sh
#!/usr/bin/ksh

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

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

Example 3:

#!/usr/bin/ksh

for i in `ls -aF`;

do
print "Files are:$i";
done

 

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

#!/usr/bin/ksh
###i=0;
while [[ $i -lt 10 ]];     do
    echo $i ;
    (( i += 1 ));
done

 

The output will be:

shanky@linux-host:/home/shanky:> ./whileLoop.ksh
0
1
2
3
4
5
6
7
8
9



 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


#!/bin/sh
i=1;
if [[ $# -eq 0 ]]; then
        echo "Usage: $0 <number>";
        exit 0;
fi
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
        fi
        i=$(($i+1)); #increment i by 1
done
echo ""
echo ""


 

Output:

[root@HYDBMW tmp]# ./factor.sh 643
Factors of 643 are:
1 643

[root@HYDBMW 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: 2356 | 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:


[2017-08-22][Open System-Linux]
Difference between tailf and tail -f in Linux
[2015-06-16][Open System-Linux]
Alien command : convert files from one form to another, install binary packages
[2014-10-26][Open System-Linux]
XMLLINT command in linux : a validating XML parser
[2014-12-16][Open System-Linux]
CUT command in Linux : cut the file vertically
[2015-08-18][Open System-Linux]
How to open a PDF file or a Postscript file in Linux - Evince Document viewer?

Total comments: 2
avatar
1
1 Piyu • 7:59 PM, 2014-05-13
wow. great script for begineers.
avatar
0
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
Multiline
comment
'
avatar