Articles

# 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:

1. Take two numbers from the user.
2. Store in two separate variables.
3. Use ‘if-else’ statements or ‘ternary’ operator to check which is large.
4. Here, we will just print the big.
5. You can use ‘flag’ to which will be initialize in ‘if-else’ condition.
6. 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.

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:"
echo -n "Second number:"
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.

Shell Script Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com