Skip to main content

Conditional Logic: if / then / elif / else / fi

Bash provides an if command to support conditional logic:

if LIST1
then
LIST2
fi

If the command or commands in LIST1 execute successfully and return an exit status code of 0, then the commands in LIST2 are executed.

For example, you could use a grep command as LIST1 and an echo command as LIST2:

if grep -q "OPS102" courses.txt
then
echo "The course code 'OPS102' was found in the file."
fi

The if command also supports the else keyword:

if grep -q "OPS102" courses.txt
then
echo "The course code 'OPS102' was found in the file."
else
echo "The course code 'OPS102' was NOT found in the file."
fi

It also supports the elif (else-if) keyword:

if grep -q "OPS102" courses.txt
then
echo "The course code 'OPS102' was found in the file."
elif grep -q "ULI101" courses.txt
then
echo "The course code 'ULI101' was found in the file.
else
echo "Neither 'OPS102' nor 'ULI101' was found in the file."
fi

Putting this all together, you could have a script like this:

#!/usr/bin/bash

read -p "Enter a filename: " FILE

if grep -q "OPS102" "$FILE"
then
echo "The course code 'OPS102' was found in the file $FILE."
elif grep -q "ULI101" courses.txt
then
echo "The course code 'ULI101' was found in the file $FILE.
else
echo "Neither 'OPS102' nor 'ULI101' was found in the file $FILE."
fi