Home » Linux/Unix » Linux if-then-else Condition in Shell Script Example

Linux if-then-else Condition in Shell Script Example

In Linux, learn how to use if-then-else condition in a shell script through examples.

An if-then-else statement, return a zero exit code if the command is successful and if the command fails returns a non-zero value. If the command returns the non-zero exit code, the bash shell just moves on to the next command in the shell script. The following is the syntax of the Linux if-then-else condition:

if-then-else Statement Syntax

if command
then 
   commands
else
   commands
fi

Linux if-then-else Condition Shell Script Examples

To demonstrate if-then-else statement examples, I am using the text file named foxfile.txt, which stored in the folder /home/vin/test and the following are the contents of this file:

foxfile.txt

A quick brown Fox jumps right over the lazy dog.
Foxes are wild animals.
The hunting dogs followed the scent of the fox.

A Simple if Condition

In the following shell script example, it will check for the string "animals" in the foxfile.txt using the grep command in the if condition and if the string found then it will print that the string found else will print that the string not found.

iftest1.sh

#!/bin/bash

srchstr="animals"

if grep $srchstr /home/vin/test/foxfile.txt 
then
   echo "String $srchstr found in file foxfile."
else
   echo "String $srchstr not found in file foxfile."
fi

Make the file executable (one-time activity)

chmod +x iftest1.sh

Test

./iftest1.sh

Output

Foxes are wild animals.
String animals found in file foxfile.

Nested if Condition

In the below shell script example, it will check for the string "animals", and if found the string then it will check if "Foxes" exists if this string also exists then it will print the whole content of the foxfile.txt with line number using the cat command.

nestedif.sh

#!/bin/bash

srchstr="animals"
srchfox="Foxes"

if grep $srchstr /home/vin/test/foxfile.txt
then
  echo "String $srchstr found in file foxfile."
  if grep $srchfox /home/vin/test/foxfile.txt
  then
     echo "String $srchfox also exists in the file. Below are the whole content of the file."
     cat -n /home/vin/test/foxfile.txt
  fi
else
  echo "String $srchstr not found in file foxfile."
fi

Make it executable

chmod +x nestedif.sh

Test

./nestedif.sh

Output

Foxes are wild animals.
String animals found in file foxfile.
Foxes are wild animals.
String Foxes also exists in the file. Below are the whole content of the file.
     1	A quick brown Fox jumps right over the lazy dog.
     2	Foxes are wild animals.
     3	The hunting dogs followed the scent of the fox.

See also: