Course: Network and System Administration

In Class Lab: 19

Name: Decisions in shell scripts with if, else and elif

Objective: Check the arguments a script is given, ask the user for input with read, and choose between two or more paths with if, else and elif. Make decisions from a command's exit status, make your scripts stop safely when something goes wrong with set -euo pipefail, add a -h and --help option, and save it all in your template and your GitLab repository.

In Lab 11 you wrote your first scripts. You made a template, read arguments with $1 and $@, and used if with exit to answer night differently from everything else. Lab 11 also left you with three promises: you would learn to check for missing arguments, to make decisions from an exit status ($?), and to stop a script when something goes wrong. This lab keeps all three.

if on its own can only do something or skip it. Real scripts usually need to choose between things: right or wrong, too high or too low, running or stopped. That is what else and elif are for. In Lab 18 you checked services with systemctl is-active. By the end of this lab, a script can make that check for you.

Note: This lab is done on your development server, NOT your production server. Connect with SSH from Terminal or PuTTY and log in as your own user.

How to use the hints

Some steps give you every command. Others give you a Goal and ask you to work out the commands yourself. If you get stuck, open the hint. Once you have an answer, or if you are really stuck, open the solution and compare it with your own.

Lab overview

  1. Part 1: Check the arguments - Task 1
  2. Part 2: Two paths with else - Task 2
  3. Part 3: More than two paths with elif - Task 3
  4. Part 4: A longer elif chain - Task 4
  5. Part 5: Decide with an exit status - Task 5
  6. Part 6: Stop when something goes wrong - Task 6
  7. Part 7: Add a help option - Task 7
  8. Part 8: Save your scripts in GitLab - Task 8

If you get stuck, check the Troubleshooting section at the end of this lab.

The examples in this lab use the username angus.


Part 1: Check the arguments

Create a workspace

Keep this lab's scripts together, as in Labs 15 to 17:

mkdir -p ~/inclass/lab-19 cd ~/inclass/lab-19

Every script in this lab starts as a copy of the template you made in Lab 11, Part 2. Fill in its header each time.

Special variables

In Lab 11 you used $1, $@ and $*. Bash sets a few more variables every time a script runs:

Variable Holds
$0 The name of the script, the way it was run, such as ./arguments.sh.
$1, $2, $3 The first, second and third arguments, and so on.
$# How many arguments were given.
$* All the arguments, joined into one string.
$@ All the arguments, kept as separate words.

A script with mistakes

Copy the template:

cp ~/scripts/shell/template.sh arguments.sh vim arguments.sh

Fill in the header, and add the lines below it, so the whole file looks like this. The echo lines at the bottom use the wrong variables. Type them exactly as shown. You fix them in Task 1.

#!/bin/bash # Title: arguments.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: Demonstrate the bash special variables. # Update: if [ "$#" -ne 3 ]; then echo "Please enter three arguments: a city name, a day (such as Wednesday) and a month (such as June)." echo "Exiting now." exit 1 fi echo "The script name is: $1" echo "The total arguments provided was: $0" echo "The day provided was: $*" echo "All the arguments provided were: $#"
Part What it does
[ "$#" -ne 3 ] Is the number of arguments not equal to 3? -ne compares two numbers.
exit 1 Stops the script with exit status 1. Any number other than 0 means "something went wrong". In Lab 11 you used exit 0, because the script had done its job. Here the user made a mistake, so the script says so.

Compare numbers with these operators inside [ ]. You use the rest of them later in this lab:

Operator Means Operator Means
-eq equal -ne not equal
-gt greater than -lt less than
-ge greater than or equal -le less than or equal

To compare text, use = and !=, as you did with "$1" = "night" in Lab 11.

Make the script executable. Run it with too few arguments, check the exit status with $? from Lab 11, then run it with three:

chmod u+x arguments.sh ./arguments.sh Seattle Monday echo $? ./arguments.sh "San Diego" Wednesday June
Please enter three arguments: a city name, a day (such as Wednesday) and a month (such as June). Exiting now. 1 The script name is: San Diego The total arguments provided was: ./arguments.sh The day provided was: San Diego Wednesday June All the arguments provided were: 3

arguments output

Note: The screenshot was taken with an older version of the script, so its first message and folder name are different. The four lines at the bottom are the same.

The quotes keep San Diego as one argument, as in Lab 11, so $# is 3, not 4.

Task 1: Fix the variables

Goal: Fix the four echo lines in arguments.sh so that each one prints what it says: the script name, the number of arguments, the day, and all the arguments. Run it again with "San Diego" Wednesday June.

Hint
Solution
echo "The script name is: $0" echo "The total arguments provided was: $#" echo "The day provided was: $2" echo "All the arguments provided were: $*"
./arguments.sh "San Diego" Wednesday June
The script name is: ./arguments.sh The total arguments provided was: 3 The day provided was: Wednesday All the arguments provided were: San Diego Wednesday June

Going further: Add a line for the month, with $3. Then run the script as ~/inclass/lab-19/arguments.sh "San Diego" Wednesday June. $0 now shows the full path, because $0 is the name the way you typed it.


Part 2: Two paths with else

else gives an if a second path: the lines that run when the test is false. Exactly one of the two paths runs, every time.

Ask the user with read

So far your scripts got everything from arguments. read asks the user a question while the script runs, and saves the answer in a variable.

Create a number guessing game:

cd ~/inclass/lab-19 cp ~/scripts/shell/template.sh guess.sh vim guess.sh

Fill in the header, and add these lines below it:

myguess=3 echo "Welcome to the number guessing game!" read -sp "Enter your guess between 1-5: " yourguess echo if [ "$myguess" != "$yourguess" ]; then echo "$yourguess was not right" echo "My number was $myguess" else echo "$yourguess was right" fi
Part What it does
read Waits for the user to type a line and press Enter.
-p "Enter your guess..." Prints a prompt first, on the same line as the answer.
-s Silent: what the user types is not shown on the screen, as with a password.
yourguess The variable that gets the answer. There is no $ here, because you are setting it, as in name=$1.
echo With nothing after it, prints an empty line. With -s, the Enter isn't shown either, so without this the next message would start on the prompt's line.
!= Not equal, for text.
else Everything between else and fi runs when the test is false.

Make it executable, and run it a few times with right and wrong answers:

chmod u+x guess.sh ./guess.sh ./guess.sh
Welcome to the number guessing game! Enter your guess between 1-5: 4 was not right My number was 3

Question: != compares text. What does the script say if you type 03? Why?

Answer

03 was not right. As text, 03 and 3 are different strings, even though they are the same number. In Part 3 you compare numbers with -gt and -lt, which treat 03 as 3.

Task 2: A secret word

Goal: Write a script called secret.sh that asks for a secret word without showing it as it is typed. If the word is linux, print Access granted. Otherwise print Access denied and stop with exit status 1. Test both answers, and check the exit status each time.

Hint
Solution
cp ~/scripts/shell/template.sh secret.sh vim secret.sh
secret="linux" read -sp "Enter the secret word: " answer echo if [ "$answer" = "$secret" ]; then echo "Access granted" else echo "Access denied" exit 1 fi
chmod u+x secret.sh ./secret.sh echo $? ./secret.sh echo $?

The right word gives Access granted and 0. Anything else gives Access denied and 1. Linux is denied too, because text comparisons are case sensitive, as you saw in Lab 11.

Warning: This is only practice. Never keep a real password in a script. Anyone who can read the file, which ls -l shows you, as in Lab 6, can read the password.


Part 3: More than two paths with elif

elif is short for else if. It adds another test, which is only tried if every test above it was false. The else at the end catches anything that matched none of them.

Give the player a clue:

cd ~/inclass/lab-19 cp ~/scripts/shell/template.sh guess-tips.sh vim guess-tips.sh

Add these lines below the header. This version has a mistake in it, on purpose:

myguess=3 echo "Welcome to the number guessing game!" read -sp "Enter your guess between 1-5: " yourguess echo if [ "$myguess" -gt "$yourguess" ]; then echo "$yourguess was too high" elif [ "$myguess" -lt "$yourguess" ]; then echo "$yourguess was too low" else echo "$yourguess was right" fi
Part What it does
if [ "$myguess" -gt "$yourguess" ] First test: is my number greater than your guess?
elif [ ... -lt ... ] Only tried if the first test was false.
else Only reached if both tests were false, so the numbers are equal.

Make it executable, and try 1, 5 and 3:

chmod u+x guess-tips.sh ./guess-tips.sh
Welcome to the number guessing game! Enter your guess between 1-5: 1 was too high

1 is lower than 3, not higher. The clues are back to front.

Common Pitfall: Use -gt and -lt to compare numbers inside [ ], never > and <. To the shell, > is a redirect, from Lab 5. [ "$myguess" > "$yourguess" ] creates a file named after your guess, and the test is always true. If a file called 1 or 5 turns up in your directory, this is why. Delete it with rm.

Task 3: Fix the clues

Goal: Fix guess-tips.sh so that a guess that is too low says too low, and a guess that is too high says too high. Test it with 1, 5 and 3.

Hint
Solution

Put the guess first in each test, so the test reads the same way as the message:

if [ "$yourguess" -gt "$myguess" ]; then echo "$yourguess was too high" elif [ "$yourguess" -lt "$myguess" ]; then echo "$yourguess was too low" else echo "$yourguess was right" fi
1 was too low 5 was too high 3 was right

Another way: Leave the tests as they were, and swap the two messages. That works too, but "if my number is greater than your guess, your guess was too low" is harder to read. Code that reads like the sentence it means has fewer mistakes.

Going further: Type abc as your guess. -gt needs numbers, so you get integer expression expected. Then try 03: it is right this time, because -gt and -lt compare numbers, not text. To let the player guess again until they get it right, you need a loop, which you learn in Lab 22.


Part 4: A longer elif chain

You can have as many elif blocks as you need. The shell tries each test from the top, runs the first one that is true, and skips the rest.

cd ~/inclass/lab-19 cp ~/scripts/shell/template.sh day.sh vim day.sh

Add these lines below the header:

read -p "What day is it? " day if [ "$day" = "Monday" ]; then echo "oof, the week is just starting" elif [ "$day" = "Friday" ]; then echo "nice, you made it through the week" elif [ "$day" = "Sunday" ]; then echo "Well, hopefully you got some chill time this weekend" else echo "Sorry, I don't recognize the day you entered" fi

This time read has no -s, so you can see what you type.

chmod u+x day.sh ./day.sh ./day.sh

Try Friday, Tuesday and friday. Only exact matches work: friday gets the else message, because the comparison is case sensitive.

Note: You may see then on the line below the test in other scripts:

if [ "$day" = "Monday" ] then

That works too. The ; in if [ ... ]; then ends the test, so then can share its line. Pick one style and keep to it.

Task 4: Add two more days

Goal: Add two more elif blocks to day.sh, each with its own message, for two days the script doesn't know yet. Test both, plus a day that still falls through to the else.

Hint
Solution

For example, add these above the else:

elif [ "$day" = "Wednesday" ]; then echo "Halfway there" elif [ "$day" = "Saturday" ]; then echo "Enjoy your weekend"
./day.sh
What day is it? Wednesday Halfway there

The else must stay last. It catches everything that the tests above it didn't, so an elif below it could never be reached, and bash rejects it with a syntax error.


Part 5: Decide with an exit status

What if really tests

Every command leaves an exit status behind, as you saw with $? in Lab 11: 0 for success, anything else for a problem. In Lab 18 you checked services with systemctl is-active. Check its exit status too. nftables has been stopped since Lab 14:

systemctl is-active nginx echo $? systemctl is-active nftables echo $?
active 0 inactive 3

Here is the secret behind every if you have written: if runs the command after it, and checks its exit status. 0 means true, and runs the then path. Anything else means false.

[ is a command too, as the Common Pitfall in Lab 11 said. It exits with 0 when its test is true:

[ 5 -gt 3 ] echo $? [ 2 -gt 3 ] echo $?

The first prints 0, the second 1. So if doesn't need [ ] at all. Any command can go after if.

Check a service

cd ~/inclass/lab-19 cp ~/scripts/shell/template.sh service-check.sh vim service-check.sh

Add these lines below the header:

service=$1 if systemctl is-active --quiet "$service"; then echo "$service is running" else echo "$service is NOT running" exit 1 fi
Part What it does
systemctl is-active --quiet "$service" Checks the service, but --quiet prints nothing. The if only needs the exit status, and the script prints its own message.
no [ ] The command itself is the test.
exit 1 The script passes the bad news on, so another script or a person can check its $?.
chmod u+x service-check.sh ./service-check.sh nginx ./service-check.sh chronyd ./service-check.sh nftables echo $?
nginx is running chronyd is running nftables is NOT running 1

Task 5: Check that a user exists

In Lab 11, Task 2, userinfo.sh nobodyhere printed an error from id, and carried on anyway.

Goal: Write a script called user-check.sh that takes a username as its first argument, and prints exists or does not exist, using the exit status of id. Only your script's message should appear on the screen, never the output of id. A missing user should end with exit status 1. Test it with kthompson and nobodyhere.

Hint
Solution
cp ~/scripts/shell/template.sh user-check.sh vim user-check.sh
user=$1 if id "$user" &> /dev/null; then echo "$user exists" else echo "$user does not exist" exit 1 fi
chmod u+x user-check.sh ./user-check.sh kthompson ./user-check.sh nobodyhere echo $?
kthompson exists nobodyhere does not exist 1

&> /dev/null sends both the normal output and the errors of id away. Its exit status still reaches the if.

Another way: grep with -q, for quiet, prints nothing and only sets the exit status: if grep -q "^$user:" /etc/passwd; then. The pattern is the one from Lab 3 and Lab 11.

Going further: ! in front of a command reverses its exit status. if ! id "$user" &> /dev/null; then runs the then path when the user does not exist.


Part 6: Stop when something goes wrong

By default, bash keeps going after a command fails. It also treats a misspelled variable as empty, without a word. In a script that deletes or changes files, that can do real damage. Three settings fix this.

See the problem

cd ~/inclass/lab-19 cp ~/scripts/shell/template.sh safety.sh vim safety.sh

Add these lines below the header. The $nmae is a typo on purpose:

ls /nosuchdir echo "Step 1: after ls" name="Ada" echo "Step 2: hello $nmae" grep "^nosuchuser:" /etc/passwd | wc -l echo "Step 3: after the pipe"
chmod u+x safety.sh ./safety.sh echo $?
ls: cannot access '/nosuchdir': No such file or directory Step 1: after ls Step 2: hello 0 Step 3: after the pipe 0

Three things went wrong: ls failed, the variable name was misspelled, and grep found nothing. The script ran to the end anyway, and its exit status is 0, "success".

set -e: stop after a failed command

Add this line below the header, above the ls line:

set -e
./safety.sh echo $?

The script stops right after the ls error, and Step 1 is never printed. The exit status is 2, from ls. Put a # in front of the ls line, so the script can get further, and run it again.

set -u: stop on unset variables

Change the set line to:

set -eu
./safety.sh
Step 1: after ls ./safety.sh: line 12: nmae: unbound variable

Your line number may be different. Bash names the misspelled variable for you. Fix the typo so the line says $name, and run the script again. It runs to the end, and Step 3 is printed, even though grep found nothing.

set -o pipefail: a pipe fails if any part fails

The exit status of a pipe is the status of its last command. Here that is wc, which counted 0 lines with no trouble, so the pipe "succeeded". Change the set line one more time:

set -euo pipefail
./safety.sh echo $?
Step 1: after ls Step 2: hello Ada 0 1

wc still prints 0, because both sides of a pipe run. But now the pipe's status is 1, from grep, and the script stops before Step 3.

Setting What it does
set -e Exit as soon as a command fails.
set -u Treat an unset variable as an error, instead of an empty value.
set -o pipefail A pipe fails if any command in it fails, not only the last one.
set -euo pipefail All three in one line. Put it at the top of a script, below the header.

Note: set -e doesn't stop the script when a command fails in a test, such as after if or elif. That is why service-check.sh and user-check.sh would still work with it: a failed check there is an answer, not a mistake.

Common Pitfall: With set -e, a grep that finds nothing stops the script, because "no match" is exit status 1. That is what you want when the match must be there. When "no match" is a normal answer, put the grep after an if, as in Task 5.

Task 6: Make service-check.sh safe

Goal: Add set -euo pipefail to service-check.sh, and run it with no argument. Read the error. Then add a check from Part 1, so that a missing argument prints a usage line, Usage: ./service-check.sh <service>, and stops with exit status 1. Test it with no argument, and with nginx.

Hint
Solution
./service-check.sh: line 8: $1: unbound variable

Add the set line and the check above service=$1:

set -euo pipefail if [ "$#" -ne 1 ]; then echo "Usage: $0 <service>" exit 1 fi service=$1
./service-check.sh echo $? ./service-check.sh nginx
Usage: ./service-check.sh <service> 1 nginx is running

<service> in a usage line is a common way to say "put a service name here". You saw [...] for "optional" in Lab 11.


Part 7: Add a help option

Most commands accept -h or --help, as you saw in Lab 0. In Lab 11 you answered help. Real commands usually accept a short option, -h, and a long option, --help, just like ls -a and ls --all.

Add this block to service-check.sh, below the set line and above the $# check:

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then echo "Usage: $0 [ -h | --help ] <service>" echo " Report whether a systemd service is running." echo " -h, --help Show this help message and exit." exit 0 fi
Part What it does
[[ ... ]] Bash's own test. It works like [ ], but lets you join tests inside it. It only works in bash, which your shebang asks for.
== Equal, for text. Inside [[ ]], == and = mean the same thing. Inside [ ], use =.
|| Or: true if either test is true.
"${1:-}" The first argument, or an empty string if there isn't one. Without it, running the script with no argument would stop here with unbound variable, because of set -u.
$0 The script's name, so the usage line is right even if you rename the file.
exit 0 Showing help is not an error, so the status is 0.

The help block goes first, so -h gets help before anything else can complain. That is also why it needs ${1:-}: it runs before the $# check, when there might be no $1.

./service-check.sh -h ./service-check.sh --help ./service-check.sh ./service-check.sh sshd
Usage: ./service-check.sh [ -h | --help ] <service> Report whether a systemd service is running. -h, --help Show this help message and exit.

Question: The help exits with 0, but a missing argument exits with 1. Why the difference?

Answer

When you ask for help, the script did exactly what you asked, so it succeeded. When the argument is missing, the script couldn't do its job. A person, or another script, checking $? can tell the two apart.

Task 7: Update your template

Your template from Lab 11 is where every new script starts. Put what you learned in it, so every script starts safe. Lab 22 starts from this template too.

Goal: Add the set -euo pipefail line to ~/scripts/shell/template.sh, below the header. Under it, add a general help block, Usage: $0 [ -h | --help ] and the -h, --help line, but with every line of the block commented out, so you only switch it on when a script needs it. Prove the template still runs, with exit status 0.

Hint
Solution
vim ~/scripts/shell/template.sh
#!/bin/bash # Title: <script_name>.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: <Describe script purpose> # Update: <Add update notes here> set -euo pipefail # stop on errors, unset variables and failed pipes #if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then # echo "Usage: $0 [ -h | --help ]" # echo " -h, --help Show this help message and exit." # exit 0 #fi
bash ~/scripts/shell/template.sh echo $?

It prints nothing, and echo $? prints 0.

Tip: To switch the help block on in a new script, Vim's visual block mode removes the # from several lines at once. Put the cursor on the # of #if, press Ctrl+V, press j four times to reach #fi, then press x. To comment lines out again: Ctrl+V, select the lines with j, type I#, then press Esc.


Part 8: Save your scripts in GitLab

As in Lab 11, Part 6, your scripts belong in your GitLab repository.

Start an agent, load your dev01 key, change into your repository and pull first:

eval "$(ssh-agent -s)" ssh-add cd ~/git/gitlab/itfdn-140-inclass-$USER git pull

Your Lab 11 scripts are in scripts/shell. Keep this lab's scripts in their own folder, so you can tell them apart:

mkdir -p scripts/lab-19 cp ~/inclass/lab-19/*.sh scripts/lab-19/ ls -l scripts/lab-19 git add scripts/lab-19 git commit -m "add lab 19 if, else and elif scripts" git push

If a file called 1, 3 or 5 turned up in ~/inclass/lab-19 from the Part 3 Common Pitfall, the *.sh leaves it behind.

Task 8: Push your new template

Goal: Copy your updated template.sh over the copy in your repository's scripts/shell folder. Show exactly what changed before you commit, then commit and push it. Check in GitLab that the template has your set line.

Hint
Solution
cp ~/scripts/shell/template.sh scripts/shell/ git diff git add scripts/shell/template.sh git commit -m "template.sh: add set -euo pipefail and a help block" git push git log --oneline

git diff shows the new lines with a + in front. When you have finished with Git for today, stop your agent with eval "$(ssh-agent -k)", as in Lab 7.


Lab summary

You have now:

Questions to consider

Discuss these with others in class:

  1. Why does guess.sh say 03 is wrong, while the fixed guess-tips.sh says it is right?
  2. What goes wrong if you use > instead of -gt inside [ ]?
  3. Before Part 6, safety.sh hit three problems but finished with exit status 0. Why is that dangerous for a script that runs with nobody watching, such as a scheduled job?
  4. When is a command that "fails" not really a mistake? How do you stop set -e from ending the script then?
  5. Why does a help option exit with 0, while a usage error exits with 1?
  6. Which checks from Labs 13 to 18 could you turn into scripts like service-check.sh?
  7. Why is it a bad idea to keep a real password in a script, even one only you use?

Troubleshooting

Q. ./guess.sh says "Permission denied".

A. The script isn't executable. Run chmod u+x guess.sh, as in Lab 11.

Q. My answer and the next message are on the same line.

A. read -s doesn't show the Enter you pressed. Add an echo with nothing after it, below the read line.

Q. I get "integer expression expected".

A. -gt, -lt, -eq and -ne only compare whole numbers. Something that isn't a number, such as abc or an empty answer, reached the test. Type a number, or compare text with = and != instead.

Q. I get "unary operator expected" or "too many arguments".

A. A variable inside [ ] is missing its double quotes. Without them, an empty variable disappears, and a value with spaces becomes several words. Write "$day", not $day.

Q. A file called 1, 3 or 5 appeared in my directory.

A. You used > or < inside [ ]. The shell treated it as a redirect, from Lab 5. Use -gt and -lt, and delete the file with rm.

Q. I get "$1: unbound variable".

A. The script has set -u and was run with no argument. Check $# first, as in Task 6, or write "${1:-}" where the argument may be missing, as in Part 7.

Q. My script stops partway through, with no error message.

A. With set -e, a command that fails stops the script, and some commands fail quietly. grep finding nothing is the usual one. Run the same command at the prompt and check echo $?. If its failure is a normal answer, test it with if, as in Part 5.

Q. I get "syntax error near unexpected token" or "syntax error: unexpected end of file".

A. An if block is broken. Check for an elif below the else, a missing then, or a missing fi at the end. Every if needs its own fi.

Q. My script works here, but on another Linux system I get "[[: not found".

A. On RHEL, sh is bash, so sh script.sh still understands [[ ]]. On some other systems, such as Ubuntu, sh is a smaller shell that doesn't. Run scripts as ./script.sh, so the #!/bin/bash line picks the shell.

Q. service-check.sh says a service is NOT running, but I think it is.

A. Check the name with systemctl status <name>, as in Lab 18. The time service is chronyd, not chrony, and a misspelled name counts as not running.

Q. git push is rejected.

A. Someone, perhaps you in the GitLab web page, changed the repository. Run git pull, then git push again, as in Lab 10.

If you are still stuck, post your question, and the commands and output you are seeing, in this week's Teams channel, or reach out by email for help.


Lab complete