Labs ICT
Pro Login

Shell Conditionals

Scripts get interesting when they make decisions. Is a file there? Is the user root? Did the last command succeed? Conditionals let your script check these things and do different things based on the answer.

If/then/fi

The basic structure is if followed by a command, then, the code to run if it succeeds, and fi to close. Yes, fi is if backwards. The test command is what you will usually put after if.

#!/bin/bash
if test -f "notes.txt"
then
    echo "notes.txt exists"
fi
Try it Yourself →

The test command and [ ]

test and [ ] are the same thing. The brackets version is more common. Notice the spaces around the brackets — they are required. The closing bracket needs a space before it too.

#!/bin/bash
if [ -f "notes.txt" ]
then
    echo "notes.txt is a regular file"
fi

if [ -d "mydir" ]
then
    echo "mydir is a directory"
fi

if [ -e "something" ]
then
    echo "something exists (file or dir)"
fi

Other useful tests: -f checks for a regular file, -d checks for a directory, -e checks for existence of anything, -z checks if a string is empty, -n checks if a string is not empty.

Try it Yourself →

Else and elif

Add else for the fallback case and elif for additional conditions. The full chain looks like this:

#!/bin/bash
if [ "$1" = "start" ]
then
    echo "Starting service..."
elif [ "$1" = "stop" ]
then
    echo "Stopping service..."
else
    echo "Usage: $0 start|stop"
fi
Try it Yourself →

Combining conditions

Use && for AND and || for OR inside the test brackets. Or combine multiple test commands with && and || between them.

#!/bin/bash
if [ -f "config.txt" ] && [ -r "config.txt" ]
then
    echo "config.txt exists and is readable"
fi

if [ "$USER" = "root" ] || [ "$UID" -eq 0 ]
then
    echo "You are root"
fi
Try it Yourself →