> ## Content Index
> Fetch the complete content index at: https://itsfoss.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Chapter #7: If Else Statement
- URL: https://itsfoss.com/bash-if-else/
- Published: 2023-07-24T12:13:10.000Z
- Updated: 2024-07-24T04:29:14.000Z
- Description: If this, then that else something else. Doesn't make sense? It will after you learn about the if-else statements in bash shell scripting.
- Author: Abhishek Prakash
- Tags: Bash Basics, #docs

Bash supports if-else statements so that you can use logical reasoning in your shell scripts.

The generic if-else syntax is like this:

```
if [ expression ]; then

  ## execute this block if condition is true else go to next

elif [ expression ]; then

  ## execute this block if condition is true else go to next

else 

  ## if none of the above conditions are true, execute this block

fi
```

As you can notice:

- `elif` is used for "else if" kind of condition
- The if else conditions always end with `fi`
- the use of semicolon `;` and `then` keyword

Before I show the examples of if and else-if, let me share common comparison expressions (also called test conditions) first.

## Test conditions

Here are the test condition operators you can use for numeric comparison:

| Condition | Equivalent to true when                           |
| --------- | ------------------------------------------------- |
| $a -lt $b | $a < $b ($a is **l**ess **t**han $b)              |
| $a -gt $b | $a > $b ($a is **g**reater **t**han $b)           |
| $a -le $b | $a <= $b ($a is **l**ess or **e**qual than $b)    |
| $a -ge $b | $a >= $b ($a is **g**reater or **e**qual than $b) |
| $a -eq $b | $a is equal to $b                                 |
| $a -ne $b | $a is not equal to $b                             |

If you are comparing strings, you can use these test conditions:

| Condition    | Equivalent to true when |
| ------------ | ----------------------- |
| "$a" = "$b"  | $a is same as $b        |
| "$a" == "$b" | $a is same as $b        |
| "$a" != "$b" | $a is different from $b |
| \-z "$a"     | $a is empty             |

There are also conditions for file type check:

| Condition | Equivalent to true when |
| --------- | ----------------------- |
| \-f $a    | $a is a file            |
| \-d $a    | $a is a directory       |
| \-L $a    | $a is a link            |

Now that you are aware of the various comparison expressions let's see them in action in various examples.

## Use if statement in bash

Let's create a script that tells you if a given number is even or not.

Here's my script named `even.sh`:

```
#!/bin/bash

read -p "Enter the number: " num

mod=$(($num%2))

if [ $mod -eq 0 ]; then
	echo "Number $num is even"
fi
```

The modulus operation (%) returns zero when it is perfectly divided by the given number (2 in this case).

🚧

Pay special attention to space. There must be space between the opening and closing brackets and the conditions. Similarly, space must be before and after the conditional operators (-le, == etc).

Here's what it shows when I run the script:

![Running a script with if statement example in bash](https://itsfoss.com/content/images/2023/07/bash-if-example.png)

Did you notice that the script tells you when a number is even but it doesn't display anything when the number is odd? Let's improve this script with the use of else.

## Use if else statement

Now I add an else statement in the previous script. This way when you get a non-zero modulus (as odd numbers are not divided by 2), it will enter the else block.

```
#!/bin/bash

read -p "Enter the number: " num

mod=$(($num%2))

if [ $mod -eq 0 ]; then
	echo "Number $num is even"
else
	echo "Number $num is odd"
fi
```

Let's run it again with the same numbers:

![Running a bash script that checks odd even number](https://itsfoss.com/content/images/2023/07/bash-if-else-example.png)

As you can see, the script is better as it also tells you if the number is odd.

## Use elif (else if) statement

Here's a script that checks whether the given number is positive or negative. In mathematics, 0 is neither positive nor negative. This script keeps that fact in check as well.

```
#!/bin/bash

read -p "Enter the number: " num

if [ $num -lt 0 ]; then
	echo "Number $num is negative"
elif [ $num -gt 0 ]; then
	echo "Number $num is positive"
else
	echo "Number $num is zero"
fi
```

Let me run it to cover all three cases here:

![Running a script with bash elif statement](https://itsfoss.com/content/images/2023/07/bash-elif.png)

## Combine multiple conditions with logical operators

So far, so good. But do you know that you may have multiple conditions in a single by using logical operators like AND (&&), OR (||) etc? It gives you the ability to write complex conditions.

Let's write a script that tells you whether the given year is a leap year or not.

Do you remember the conditions for being a leap year? It should be divided by 4 but if it is divisible by 100, it's not a leap year. However, if it is divisible by 400, it is a leap year.

Here's my script.

```
#!/bin/bash

read -p "Enter the year: " year

if [[ ($(($year%4)) -eq 0 && $(($year%100)) != 0) || ($(($year%400)) -eq 0) ]]; then
	echo "Year $year is leap year"
else
	echo "Year $year is normal year"
fi
```

💡

Notice the use of double brackets `[[ ]]` above. It is mandatory if you are using logical operators.

Verify the script by running it with different data:

![Example of running  bash script with logical operators in if statement](https://itsfoss.com/content/images/2023/07/bash-logical-operators-in-if-else.png)

## 🏋️ Exercise time

Let's do some workout :)

**Exercise 1**: Write a bash shell script that checks the length of the string provided to it as an argument. If no argument is provided, it prints 'empty string'.

**Exercise 2**: Write a shell script that checks whether a given file exists or not. You can provide the full file path as the argument or use it directly in the script.

**Hint**: Use -f for file

**Exercise 3**: Enhance the previous script by checking if the given file is regular file, a directory or a link or if it doesn't exist.

**Hint**: Use -f, -d and -L 

**Exercise 4**: Write a script that accepts two string arguments. The script should check if the first string contains the second argument as a substring.

**Hint**: Refer to the previous chapter on [bash strings](https://itsfoss.com/bash-strings/)

You may discuss your solution in the Community:

[Practice Exercise in Bash Basics Series #7: If Else StatementsIf you are following the Bash Basics series on It’s FOSS, you can submit and discuss the answers to the exercise at the end of the chapter: Fellow experienced members are encouraged to provide their feedback to new members. Do note that there could be more than one answer to a given problem.![](https://itsfoss.community/uploads/default/optimized/1X/f274f9749e3fd8b4d6fbae1cf90c5c186d2f699c_2_180x180.png)It's FOSS Communityabhishek![](https://itsfoss.community/uploads/default/original/1X/f274f9749e3fd8b4d6fbae1cf90c5c186d2f699c.png)](https://itsfoss.community/t/practice-exercise-in-bash-basics-series-7-if-else-statements/10926?ref=itsfoss.com)

I hope you are enjoying the Bash Basics Series. In the next chapter, you'll learn about [using loops in Bash](https://itsfoss.com/bash-loops/). 

[Bash Basics #8: For, While and Until LoopsIn the penultimate chapter of the Bash Basics series, learn about for, while and until loops.![](https://itsfoss.com/content/images/size/w256h256/2022/12/android-chrome-192x192.png)It's FOSSAbhishek Prakash![](https://itsfoss.com/content/images/2023/07/bash-loops.png)](https://itsfoss.com/bash-loops/)

Keep on bashing!