Conditionals

A conditional statement provides a way to execute one set of commands or another, based on Boolean tests (or conditions). One example is the if statement, which chooses between alternatives. The simplest form is the if-then statement:

if command           If exit status of command is 0
then
  body
fi

For example, if you write a script that must be run with sudo, you can check for administrator privileges like this:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
fi

Here’s a practical example for your ~/.bash_profile file (see Tailoring Shell Behavior). Some users like to place some of their shell configuration commands (such as aliases) into a separate file, ~/.bashrc. We can tell ~/.bash_profile to load and run these commands if the file exists:

# Inside ~/.bash_profile:
if [ -f $HOME/.bashrc ]
then
  . $HOME/.bashrc
fi

Next is the if-then-else statement:

if command
then
  body1
else
  body2
fi

For example:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
else
  echo "You are an ordinary dude"
fi

Finally, we have the form if-then-elif-else, which may have as many tests as you like:

if command1
then
  body1
elif command2
then
  body2
elif ...
  ...
else
  bodyN
fi

For example:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
elif [ "$USER" = "root" ]
then
  echo "You might be the superuser"
elif [ "$bribe" -gt 10000 ]
then
  echo "You can pay to be the superuser"
else
  echo "You are still an ordinary dude"
fi

The case statement is a simplified alternative to long chains of if-then-else ...

Get Macintosh Terminal Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.