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:
ifcommandIf exit status of command is 0 thenbodyfi
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:
ifcommandthenbody1elsebody2fi
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:
ifcommand1thenbody1elifcommand2thenbody2elif ... ... elsebodyNfi
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access