Decision Making

A Shell script is a plain text file. This file contains different commands for step-by-step execution.

These commands can be written directly into the command line but from a re-usability perceptive it is useful to store all of the inter-related commands for a specific task in a single file.

Two types of decision-making statements are used within shell scripting. They are –

  • If-else statement

  • case-sac statement

If-else

If else statement is a conditional statement. It can be used to execute two different codes based on whether the given condition is satisfied or not.

There are a couple of varieties present within the if-else statement.

  • if-fi

  • if-else-fi

  • if-elif-else-fi

  • nested if-else

if-fi

if  [[ some_test ]] 

then 	
	commands
fi

Example:

#!/bin/bash 

# Bash if statement example 

read -p "What is your name? " name 

if [[ -z ${name} ]] 

then 
echo "Please enter your name!" 

fi 

if-else-fi

if  [ expression ] 

then 	
	Commands
else
	Commands
fi

Example:

#!/bin/bash 

# Bash if statement example 

read -p "What is your name? " name 

if [[ -z ${name} ]] 

then 

echo "Please enter your name!" 
else 
echo "Hi there ${name}" 

fi

if-elif-else

if  [ expression ] 

then 
	Commands
elif [ expression ] 

	commands
else
	Commands
fi

Example:

#!/bin/bash 

read -p "Enter a number: " num 

if [[ $num -gt 0 ]] ; then 

echo "The number is positive" 

elif [[ $num -lt 0 ]] ; then 

echo "The number is negative" 

else 
echo "The number is 0" 

fi

Switch-case

you can use a case statement to simplify complex conditionals when there are multiple different choices.

So rather than using a few if, and if-else statements, you could use a single case statement.

case $some_variable in 

pattern_1) 

commands 

;; 

pattern_2| pattern_3) 

commands 

;; 

*) 

default commands 

;; 
esac

Example

#!/bin/bash 

read -p "Enter the name of your car brand: " car 

case $car in 
Tesla) 
echo -n "${car}'s car factory is in the USA." 
;; 
BMW | Mercedes | Audi | Porsche) 
echo -n "${car}'s car factory is in Germany." 
;; 
Toyota | Mazda | Mitsubishi | Subaru) 
echo -n "${car}'s car factory is in Japan." 
;; 
*) 
echo -n "${car} is an unknown car brand" 
;; 

esac 

Last updated