Shell script to find the greatest of two numbers
In this shell scripting article, we will learn how to write:
-
shell script to find the greatest of two numbers
Here we require 'read', '-gt' command to compare two numbers to get greater between them.
HINTS:
In order to write shell script to find the greatest of two numbers:
-
Take two numbers from the user.
-
Store in two separate variables.
-
Use ‘if-else’ statements or ‘ternary’ operator to check which is large.
-
Here, we will just print the big.
-
You can use ‘flag’ to which will be initialize in ‘if-else’ condition.
-
Suppose if ‘flag=1’, first one is greater otherwise second one is greater.
ALGORITHM:
Given below is algorith for shell script to find the greatest of two numbers.
Read first_num
Read second_num
Check cond. If ( first_num>second)
Then
first_one is large than second_num
else
second_one is large than first_num
// if-else done.
CODE:
Shell program to find greatest of two numbers is given below:
clear
echo "a shell script to find out the large between two number."
echo -n "First number:"
read fst_num
echo -n "Second number:"
read snd_num
if test $fst_num -gt $snd_num
then
echo $fst_num is greater than $snd_num.
else
echo $snd_num is greater than $fst_num.
fi
CODE IMAGE:
Given below is the screenshot for shell program to find greatest of two numbers:
OUTPUT:
a shell script to find out the greatest among two inputs
First number:34
Second number:78
78 is greater than 34.
EXPLANATION:
Given below is explanation to shell script to find the greatest of two numbers shown above:
-
At first, I have given 34 and then it is stored in first variable name 'fst_num'.
-
'78' is given and it is stored in second variable name 'snd_num'.
-
using '-gt' command, we have compared two varbiables.
-
If 'fst_num' is greater than 'snd_num', print 'fst_num'.
-
Otherwise 'snd_num' is greater.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 09,2021