Decision Making in UNIX Shell Scripts - if Statement

The if statement allows decision making by executing a block of script when a condition is fulfilled.

Syntax:

if condition
then
commands
elif condition
then
commands
.
.
.
else
commands
fi

else and elif part of the construct (shown in italics) are optional.
You can use multiple elifs if needed. The conditions can be commands.
The return code of the command is taken as true or false condition.

Example:

The example script reads an input from std input and stores it in the variable ANSWER. It checks if the number is less-than-or-equal-to or greater-than 10 and prints an output accordingly. If the input is not a number, it prints 'Could not read the input as number" as output.

#!/bin/sh

read ANSWER?"Choose a number "

if [ $ANSWER -le 10 ]; then

print The number is less than or equal to 10
elif [ $ANSWER -gt 10 ]; then
print The number is greater than 10
else
print Could not read the input as number
fi

exit 0

Comments

Popular posts from this blog

OS/DB Migration - CMD. STR, TOC, EXT, R3load, DDLDBS.TPL and more

Fixing Inconsistent Table - Table activation fails due to inconsistency between DD and DB

301 Redirect Using SAP Web Dispatcher