If structures to execute code based on a condition

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Test commandHomeIf..else..fi →

Now, you can use the if statement to test a condition. if command The general syntax is as follows:

if condition
then
     command1 
     command2
     ...
     commandN 
fi

OR

if test var == value
then
     command1 
     command2
     ...
     commandN 
fi

OR

if test -f /file/exists
then
     command1 
     command2
     ...
     commandN 
fi

OR

 if [ condition ]
then
      command1
      command2
      ....
      ..
fi

If given condition is true than the command1, command2..commandN are executed. Otherwise script continues directly to the next statement following the if structure. Open a text editor and create the script called verify.sh:

#!/bin/bash
read -p "Enter a password" pass
if test "$pass" == "jerry"
then
     echo "Password verified."
fi

Save and close the file. Run it as follows:

chmod +x verify.sh
./verify.sh

Sample Outputs:

Enter a password : jerry
Password verified.

Run it again:

./verify.sh

Sample Output:

Enter a password : tom

The if structure is pretty straightforward. The read command will read the password and store it to variable called pass. If $pass (i.e. password) is equal to "jerry", then "Password verified." is displayed. However, if it is not equal to "jerry", the script does not print any message and script will go to the next statement. Here is another example (number.sh):

#!/bin/bash
read -p "Enter # 5 : " number
if test $number == 5 
then
    echo "Thanks for entering # 5"
fi
if test $number != 5 
then
    echo "I told you to enter # 5. Please try again."
fi

Enter # 5 : 5 Thanks for entering # 5 Save and close the file. Run it as follows:

chmod +x number.sh
./number.sh

Sample Outputs:

Enter # 5 : 5
Thanks for entering # 5

Try it again:

./number.sh

Sample Outputs:

Enter # 5 : 11
I told you to enter # 5. Please try again.
← Test commandHomeIf..else..fi →