Linux and Bash course menu
Bash if Statements: Conditions, test and case
Write conditions in Bash with if, [[ ]] and test: compare strings and numbers, check files, combine tests with && and ||, and use case statements.
On this page
if#
marks=72
if [[ $marks -ge 40 ]]; then
echo "Pass"
else
echo "Fail"
fiPassif ends with fi. The spaces inside [[ ]] are required.
elif adds more branches:
marks=85
if [[ $marks -ge 75 ]]; then
echo "Distinction"
elif [[ $marks -ge 40 ]]; then
echo "Pass"
else
echo "Fail"
fiDistinctionComparing numbers#
With (( )), you can use normal symbols:
users=12
if (( users > 10 )); then
echo "Busy"
fiBusyComparing text#
env_name="production"
if [[ "$env_name" == prod* ]]; then
echo "Careful: live system"
fi
input="1042"
if [[ "$input" =~ ^[0-9]+$ ]]; then
echo "A number"
fiCareful: live system
A numberTesting files#
if [[ -f /etc/hostname ]]; then
echo "File exists"
fi
if [[ ! -d /backup ]]; then
echo "No backup folder"
fiFile exists
No backup folder! means "not".
Combining#
Use && for "and", and || for "or":
age=20
member="yes"
if [[ $age -ge 18 && "$member" == "yes" ]]; then
echo "Allowed"
fiAllowedCommands as conditions#
if really checks a command's exit code, where 0 means success. So any command can be the condition:
if grep -q root /etc/passwd; then
echo "root exists"
fi
if ! ping -c 1 -W 1 192.0.2.1 > /dev/null 2>&1; then
echo "Host is not answering"
firoot exists
Host is not answeringShort forms#
&& runs the next command if the first succeeds, and || runs it if the first fails:
mkdir -p logs && echo "Folder ready"
ls /nothing 2> /dev/null || echo "Could not list it"Folder ready
Could not list it[[ ]] or [ ]?#
[ ] is the older form, and works in any POSIX shell. [[ ]] is Bash's improved version, with pattern matching, &&, and safer handling of empty variables. Use [[ ]] in Bash scripts. If a script starts with #!/bin/sh, use [ ].
case#
case is cleaner than a long if when one value has many options:
action="restart"
case "$action" in
start)
echo "Starting"
;;
stop)
echo "Stopping"
;;
restart|reload)
echo "Restarting"
;;
*)
echo "Unknown action"
;;
esacRestarting*) catches everything else, and ;; ends each branch.
Common mistakes#
Practice#
Practice exercise
Write a script that takes a disk usage number and prints OK below 80, WARNING from 80 to 89, and CRITICAL from 90. Test it with 72, 85 and 95 using a loop.
Show solution
for used in 72 85 95; do
if (( used >= 90 )); then
echo "$used CRITICAL"
elif (( used >= 80 )); then
echo "$used WARNING"
else
echo "$used OK"
fi
done72 OK
85 WARNING
95 CRITICALKey takeaway#
Next: Loops.
Finished this lesson?