skip to main content

SAP NetWeaver Newbie

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

No comments:

Post a Comment

Email Subscription

Get every new post into your inbox by subscribing us.

Want a reason to subscribe?
1. This sitemap might convince you to subscribe.
2. We do not misuse email IDs. We respect privacy.

© 2008 - 2017 sapnwnewbie. All rights reserved.