≡ Menu

4 Bash If Statement Examples ( If then fi, If then else fi, If elif else fi, Nested if )

Bash conditional statements perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. These statements are used to execute different parts of your shell program depending on whether certain conditions are true. The ability to branch makes shell scripts powerful.

In Bash, we have the following conditional statements:

  1. if..then..fi statement (Simple If)
  2. if..then..else..fi statement (If-Else)
  3. if..elif..else..fi statement (Else If ladder)
  4. if..then..else..if..then..fi..fi..(Nested if)

These are similar to the awk if statements we discussed earlier.

1. Bash If..then..fi statement

if [ conditional expression ]
then
	statement1
	statement2
	.
fi

This if statement is also called as simple if statement. If the given conditional expression is true, it enters and executes the statements enclosed between the keywords “then” and “fi”. If the given expression returns zero, then consequent statement list is executed.

if then fi example:

#!/bin/bash
count=100
if [ $count -eq 100 ]
then
  echo "Count is 100"
fi

2. Bash If..then..else..fi statement

If [ conditional expression ]
then
	statement1
	statement2
	.
else
	statement3
	statement4
	.
fi

If the conditional expression is true, it executes the statement1 and 2. If the conditional expression returns zero, it jumps to else part, and executes the statement3 and 4. After the execution of if/else part, execution resume with the consequent statements.

if then else fi example:

#!/bin/bash
count=99
if [ $count -eq 100 ]
then
  echo "Count is 100"
else
  echo "Count is not 100"
fi

Note: This article is part of the ongoing Bash Tutorial series.

3. Bash If..elif..else..fi

If [ conditional expression1 ]
then
	statement1
	statement2
	.
elif [ conditional expression2 ]
then
	statement3
	statement4
	.
.
.
else
	statement5
fi

You can use this if .. elif.. if , if you want to select one of many blocks of code to execute. It checks expression 1, if it is true executes statement 1,2. If expression1 is false, it checks expression2, and if all the expression is false, then it enters into else block and executes the statements in the else block.

if then elif then else fi example:

#!/bin/bash
count=99
if [ $count -eq 100 ]
then
  echo "Count is 100"
elif [ $count -gt 100 ]
then
  echo "Count is greater than 100"
else
  echo "Count is less than 100"
fi

4. Bash If..then..else..if..then..fi..fi..

If [ conditional expression1 ]
then
	statement1
	statement2
	.
else
	if [ conditional expression2 ]
	then
		statement3
		.
	fi
fi

If statement and else statement could be nested in bash. The keyword “fi” indicates the end of the inner if statement and all if statement should end with the keyword “fi”.

The “if then elif then else fi” example mentioned in above can be converted to the nested if as shown below.

#!/bin/bash
count=99
if [ $count -eq 100 ]
then
  echo "Count is 100"
else
  if [ $count -gt 100 ]
  then
    echo "Count is greater than 100"
  else
  echo "Count is less than 100"
  fi
fi

In our next article, we’ll discuss about how to use Bash conditional expressions with practical examples.

Recommended Reading

Bash 101 Hacks, by Ramesh Natarajan. I spend most of my time on Linux environment. So, naturally I’m a huge fan of Bash command line and shell scripting. 15 years back, when I was working on different flavors of *nix, I used to write lot of code on C shell and Korn shell. Later years, when I started working on Linux as system administrator, I pretty much automated every possible task using Bash shell scripting. Based on my Bash experience, I’ve written Bash 101 Hacks eBook that contains 101 practical examples on both Bash command line and shell scripting. If you’ve been thinking about mastering Bash, do yourself a favor and read this book, which will help you take control of your Bash command line and shell scripting.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Chris F.A. Johnson June 21, 2010, 3:47 pm

    The correct description of an if statement is:

    if
    then
    ….

    can be any command or list of commands, not just test (a.k.a. ‘[‘ )

    if grep date ~/.bashrc
    then
    :
    fi

    if

  • Dennis Dashkevich July 14, 2012, 11:57 am

    Chris F.A. Johnson, you must have mistyped in the last line. There should be ‘fi’.

  • phil December 12, 2012, 10:41 am

    Hey,
    you should replace the “If” by “if” – I just tried the first one and spent some time figuring out that that was the problem. It will actually print a completely useless error message, so beginners may be kind of desperate 🙂

  • Mike March 10, 2013, 5:04 pm

    Thanks for making this tutorial 🙂

    Again I echo Phil’s advice though to replace ‘If’ with ‘if’ as it causes an error.

    Cheers
    Mike

  • Meki February 18, 2014, 9:29 pm

    I tried to use this program to calculate for me but it did not work for me
    echo “This program will calculate for you”
    echo “1. Addition”
    echo “2. Subtraction”
    echo “3. Multiplication”
    echo “Please shoose 1, 2 3 ”
    read choose
    if [“shoose” -eq “1”] ; then
    echo “You choose number 1, you want to add numbers’
    else
    echo ” You choose other number”
    fi

    Thank you

  • Chris F.A. Johnson March 9, 2014, 10:27 am

    Fix this line:

    if [“shoose” -eq “1”] ; then

    It should be:

    if [ “$choose” = 1 ]; then

  • Akshay April 1, 2014, 5:20 am

    can i use if condition with cat command,,like
    if [cat /etc/group|grep ]

  • Chris F.A. Johnson April 2, 2014, 1:59 am

    The syntax is:

    if command
    then
    ….

    “[” is a command
    “cat” is a command

    Use either one, not both.

    if cat …
    then

    But *not* if cat /etc/group|grep … !!

    Use:

    if grep -q REGEX /etc/group
    then

  • DB November 28, 2014, 10:18 pm

    Hi, this tutorial is perfect for me
    But I have a question

    How to using if [$var -eq “string” ] ?

  • no one January 12, 2015, 3:14 pm

    @DB

    take care of the whitespaces if u use [ ] instead of “test”
    for example: if [ $# -lt 2 ]; then
    so after and before last bracket use a whitespace!

  • Malik March 22, 2015, 4:01 pm

    Hi,

    Would like to know if we can determine the success of the statement?

    #!/bin/bash
    {My Task Here}
    If Task was Successful =====> How is possible to report the result of above command.
    Echo “Above command was successful”
    Else
    Echo ” Something get wrong, try again”

  • David Bennett April 11, 2015, 7:49 am

    Item number 2. specifies ‘If’ with an upper-case ‘I’ this will not work.

  • Anonymous June 19, 2015, 1:27 pm

    Missing the ; after the conditional

  • Yogich November 12, 2015, 12:57 pm

    Hi..
    Having problems. Been years, since I did, this… & now, I cannot remember, squat! I’m trying to delete files that are only garbage:
    code:
    cd /foobar/foobar
    if *.dsf then rm *.dsf

    …& repeat for 2 more folders.
    I’ve tried: #

    !/bin/sh
    #
    cd foobar/foobar/foobar
    if *.dsf then rm *.dsf
    fi

    and

    if [ *.dsf ] then rm *.dsf

    Nothing, works. Get a syntax error or unexpected end, depending upon which I use. At my wits’ end. Thx, if anyone sees this, & can help.

  • Nithesh May 27, 2016, 3:20 am

    can you please explain me on writing a script which add user with uid, gid, comment from the given .txt file.

  • anthony allen February 16, 2017, 3:09 pm

    Thanks

  • vishnu March 19, 2017, 3:54 pm

    giving error in if [“$IP” -eq 209.249.130] line. Please help me out

    echo "209.249.130"
    echo "209.249.129"
    echo -en "Select IP series : " ; read IP
    echo -en "Enter remaining IP add after 209.249.129 or 209.249.130 : " ; read b
    
    if ["$IP" -eq 209.249.130]
    then
            for a in ${b}
            do
            echo "===========for 209.249.130.$a==============="
            ssh 209.249.130.${a} "free -m;echo 3 > /proc/sys/vm/drop_caches ;free -m"
            echo "===========DONE==============="
            done
    else
            for a in ${b}
            do
            echo "===========for 209.249.129.$a==============="
            ssh 209.249.129.${a} "free -m;echo 3 > /proc/sys/vm/drop_caches ;free -m"
            echo "===========DONE==============="
            done
    fi