Programming Tutorials

if...else...fi in Linux Shell Script

By: Dorris in Linux Tutorials on 2011-01-15  

In Linux shell script, if...else...fi is used to conditionally execute statements based on a condition.

The basic syntax for if...else...fi is:

if condition
then
   statements
else
   statements
fi

Here, the condition is evaluated and if it is true, the statements within the then block are executed, otherwise the statements within the else block are executed.

For example, consider the following script that checks whether a number is even or odd:

#!/bin/bash

echo "Enter a number:"
read num

if (( num % 2 == 0 ))
then
   echo "$num is even."
else
   echo "$num is odd."
fi

In this script, the read command is used to read a number from the user. Then, an if statement is used to check whether the number is even or odd. If the number is even, the echo command within the then block is executed, otherwise the echo command within the else block is executed.

Note that the ((...)) syntax is used to perform arithmetic operations and the -eq operator is used to compare two numbers for equality.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Linux )

Latest Articles (in Linux)