## if statements

If statements are conditional statements used to test whether the condition is true or false and then continue executing the script.

## if statements in Linux Shell Scripting

if condition

Syntax:

```
if condition
then
execute some commands
...
...
fi
```

Example: if.sh

```
# SOME VARIABLES
x=7

# TESTING...
if [ \$x -eq 7 ]
then
{
echo "\$x is equal to 7!"
}
fi
```

In the above example if condition was used to check if the value of x is equal to 7.
If the condition is true it will print the result.

If else condition

Syntax:

```
if condition
then
condition is true
execute some commands

else
if condition is not true
execute some commands up
fi
```

Example: if-else.sh

```
# Get the value from the user
echo " Enter a value for the variable x:"

# TESTING the value of x is 7 or not!
if [ \$x -eq 7 ]
then
{
echo "\$x is equal to 7!"
}
else
{
echo "\$x is not equal to 7!"
}
fi
```

running the script: if-else.sh
sh if-else.sh
Enter a value for the variable x:
3
3 is not equal to 7!

In the above example, based on the value of x given by you, the script will determine if the value of x is 7 or not.

Nested If else condition

Syntax:

```
if condition
then
if condition
then
.....
..
do this
else
....
..
do this
fi
else
...
.....
do this
fi
```

Example: nested-if-else.sh

```
# Get the value from the user
echo " Enter a value for the variable x:"

# TESTING the value of x is 0 or not!
if [ \$x -eq 0 ]
then
{
echo "\$x is equal to 0!"
}
else
{
if [ \$x -gt 0 ]
then
{
echo "\$x is greater than 0!"
}
else
{
echo "\$x is less than 0!"
}
fi
}
fi
```

running the script: nested-if-else.sh
./nested-if-else.sh
Enter a value for the variable x:
-10
-10 is less than 0!

Here the script can determine the value entered by you is less than 0 , greater than 0 or equal to 0. Try running this script with different values.

## Tutorials   ## Like us

I am Telson, the webmaster of Techcuriosity.com and through this site, I share my knowledge and curiosities in the Tech World.

## What We Offer

• What is ..?
• How to ..?
• Difference between ..?
• How .. works?
• ## Get in Touch

techcuriosity@gmail.com
UAE : +971-55-83-566-04
India : +91 - 9526244217

## Our Partners

• Website Design Dubai