Understanding Decisions and Loops
So far, I’ve been showing you a lot of programming techniques and constructs that are specific to shell scripting. In this section, I’ll show you some constructs that are common to most all programming languages. I’ll begin by showing you another way to make decisions.
The if. .then Construct
Although the &&
and ||
decision constructs work for simple scripts, you might want to use if . . then
constructs for anything more complex, such as when you would need to test for multiple conditions at once. For the first example, create the am_i_root_2.sh
script, which will look like this:
#!/bin/bash
if [ $(id -u) == 0 ]; then
echo "This user is root."
fi
if [ $(id -u) != 0 ]; then
echo "This user is not root."
echo "This user's name is $(id -un)."
fi
Note that each decision stanza begins with if
and ends with fi
. (Yes, that’s if
spelled backwards...