Linux shell script program to read two integer numbers and print the subtraction of both variables

Here, we are going to learn how to read two integer numbers and print the subtraction of both variables in Linux shell script?
Submitted by Nidhi, on February 14, 2021

Problem statement

Here, we will create a shell script program to read values for variables from the user and then calculate subtraction operation and print the result on the console screen.

Subtract two numbers using Linux Shell Script

The source code to create a Linux shell script program to read two integer numbers and print the subtraction of both variables is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

Source Code

#!/bin/bash

# Program name: "ReadVar.sh"
# Linux shell script program to read two integer numbers and 
# print the subtraction of both variables.

echo "Enter num1: "
read num1
echo "Enter num2: "
read num2

result=`expr $num1 - $num2`

echo "Subtraction is: $result"

Now we will save the shell script program with the "ReadVar.sh" name.

Output

$ sh ReadVar.sh 
Enter num1: 
10
Enter num2: 
2
Subtraction is: 8

Explanation

In the above program, we read values of two variables from the user and then subtract variable num2 from num1 and store the result into the result variable. After that, we printed the result on the console screen.

Linux shell script programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.