shell scripting for basic arithmetic operations

In our last post we introduced to shell scripting by knowing basic commands of shell scripting. Today we shall how to write a program in shell scripting in shell terminal and perform some basic arithmetic operations.

To write a program we need to create a file with .sh extension using the vi command. To create a a file we by vi command follow the syntax:vi file_name.sh.After creating a file press i so that you can enter the insert the data into the file.After completion of the code we need to save the file and then quit,for this press esc and write :wq and press enter your file will be saved and brought back to the terminal.If you try to compile the file you fail because you need to assign the permissions to the file for different user. To assign the permissions use the keyword chmod and by binary mansking simply assign the code 777 to your file as follows:chmod 777 file_name.sh.To compile the file use the syntax:./file_name.sh

Now we shall write a script to perform all arithmetic operations on given two numbers:

echo “Enter first value:”
read a
echo “Enter second value:”
read b
echo “Addition of $a and $b is ` expr $a + $b `”
echo “Subtraction of $a and $b is ` expr $a – $b `”
echo “Multiplication of $a and $b is ` expr $a \* $b `”
echo “Division of $a and $b is ` expr $a / $b `”
echo “Remainder of $a and $b is ` expr $a % $b `”

output:
Enter the first value:4
Enter the second value:2
Addition of 4 and 2 is 6
Subtraction of 4 and 2 is 2
Multiplication of 4 and 2 is 8
Division of 4 and 2 is 2
Remainder of 4 and 2 is 0

Hence the we performed all the arithmetic operations on given number.
You can dowmload the code from https://docs.google.com/file/d/0BxVG8Ozr6fvhVTIxN0xZT21URkk/edit?usp=sharing

Advertisements

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my Master's in Computer Science.
This entry was posted in Shell scripting and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s