Course: Network and System Administration

In Class Lab: 22

Name: Loops, options and debugging in shell scripts

Objective: Repeat commands with while and for loops, give your scripts options such as -a, first with if and shift, then with getopts, and find mistakes in a script by watching it run with bash -x and set -x.

In Lab 11 you wrote your first scripts, and in Lab 19 your scripts learned to make decisions with if, else and elif. Every script so far runs its commands once, from top to bottom. A loop runs the same commands again and again: until a counter reaches a number, until the user gets an answer right, or once for every item in a list.

You have already seen loops twice. In Lab 18 a while true loop wrote to a log file forever, in the background. In Lab 21 a for loop sent 20 requests to a container. Lab 19 also left you a promise: to let the player of the guessing game try again until they get it right. This lab explains those loops and keeps that promise.

Then you give your scripts options, the way ls -a and ls -l change what ls does, and you learn to debug a script by making bash show you every command as it runs.

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: Repeat with while - Tasks 1 and 2
  2. Part 2: Work through a list with for - Task 3
  3. Part 3: A simple option with shift - Task 4
  4. Part 4: Several options with getopts - Task 5
  5. Part 5: Debug a script with -x and -v - Task 6
  6. Part 6: Save your scripts in GitLab - Task 7

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

The examples in this lab use the username angus.


Before you start: check your template

Every script in this lab starts as a copy of ~/scripts/shell/template.sh. You last updated it in Lab 19, Task 7. Check it:

cat ~/scripts/shell/template.sh

It should look like this:

#!/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

If the set -euo pipefail line is missing, go back to Lab 19, Task 7, and add it now. If your help block uses "$1" instead of "${1:-}", change it: with set -u, "$1" stops the script when it is run with no arguments.

Create a workspace for this lab:

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

Each time you make a script in this lab, you copy the template, fill in its header, and add the lines shown below the set line. The code blocks in this lab show only those new lines.


Part 1: Repeat with while

A while loop runs a block of commands again and again, as long as a test is true. The test is the same kind you used with if in Lab 19.

Count to five

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

Fill in the header, and add these lines below the set line:

count=1 while [ "$count" -le 5 ]; do echo "Count is $count" count=$(( count + 1 )) done echo "Done. count is now $count"
Part What it does
count=1 Sets the starting value, before the loop.
while [ "$count" -le 5 ] The test. Is count less than or equal to 5? -le is from Lab 19.
do ... done The body of the loop: the commands that repeat.
$(( count + 1 )) Arithmetic. Bash works out the sum. Inside $(( )) you don't need a $ in front of the variable name.
count=$(( count + 1 )) Adds 1 to count. Without this line, the test would always be true and the loop would never end.

Each time round the loop, bash runs the test first. When the test is false, bash skips to the line after done.

Make it executable and run it:

chmod u+x count.sh ./count.sh
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done. count is now 6

Question: Why is count 6 at the end, not 5?

Answer

When count was 5, the body ran and added 1, so count became 6. The test [ 6 -le 5 ] was false, so the loop stopped. The loop always stops on the first value that makes the test false.

Common Pitfall: If you forget the line that changes count, the test is always true and the loop never ends. Press Ctrl+C to stop it, as in Lab 18.

Loop until the user says stop

In Lab 18, while true repeated forever. true is a command that always succeeds, so the test never fails. To leave a loop like that from the inside, use break:

cp ~/scripts/shell/template.sh repeat.sh vim repeat.sh
while true; do read -p "Type a word, or quit to stop: " word if [ "$word" = "quit" ]; then break fi echo "You typed: $word" done echo "Out of the loop."
Part What it does
while true Repeat forever. true always has exit status 0, the same idea as if on a command in Lab 19, Part 5.
break Leaves the loop at once. The script carries on after done.
chmod u+x repeat.sh ./repeat.sh
Type a word, or quit to stop: hello You typed: hello Type a word, or quit to stop: linux You typed: linux Type a word, or quit to stop: quit Out of the loop.

Task 1: Fix the clock

date.sh should ask for your name, then greet you every 2 seconds for 10 seconds, with the current time each time. This version runs, but it has two mistakes.

cp ~/scripts/shell/template.sh date.sh vim date.sh
read -p "Hello, enter your name: " name number=0 time=$(date +%r) while [ "$number" -lt 10 ]; do sleep 2 number=$(( number + 2 )) echo $name $time done echo "Outside the loop now and done."

date +%r prints the time as 05:11:56 PM.

chmod u+x date.sh ./date.sh

Goal: Change date.sh so that each line reads like Hello Angus it is now: 05:11:56 PM, and the time changes by 2 seconds on every line.

Hint
Solution

Move the time line inside the loop, so it runs every time round, and put the sentence in the echo line:

read -p "Hello, enter your name: " name number=0 while [ "$number" -lt 10 ]; do sleep 2 number=$(( number + 2 )) time=$(date +%r) echo "Hello $name it is now: $time" done echo "Outside the loop now and done."
Hello, enter your name: Angus Hello Angus it is now: 05:11:56 PM Hello Angus it is now: 05:11:58 PM Hello Angus it is now: 05:12:00 PM Hello Angus it is now: 05:12:02 PM Hello Angus it is now: 05:12:04 PM Outside the loop now and done.

date script output

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

The loop runs 5 times: number is 0, 2, 4, 6 and 8 when the test runs, and 10 stops it. Five times 2 seconds is 10 seconds.

Task 2: Play again until you get it right

In Lab 19, Task 3, guess-tips.sh gave one clue and stopped. Now you have a loop.

Goal: Make guess-loop.sh, a guessing game with the number 3. It asks for a guess, says too high or too low, and asks again, until the guess is right. Then it says the guess was right and stops.

Hint
Solution
cp ~/inclass/lab-19/guess-tips.sh guess-loop.sh vim guess-loop.sh
myguess=3 echo "Welcome to the number guessing game!" while true; do read -p "Enter your guess between 1-5: " yourguess 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" break fi done
./guess-loop.sh
Welcome to the number guessing game! Enter your guess between 1-5: 1 1 was too low Enter your guess between 1-5: 5 5 was too high Enter your guess between 1-5: 3 3 was right

The copy kept its execute permission, so there is no need for chmod. Change the Title line in the header.

read -p is used instead of read -sp, so you can see your guesses.

Another way: Put the test in the while line, and leave out break. With set -u, yourguess needs a value before the first test, so give it an empty one:

myguess=3 yourguess="" while [ "$yourguess" != "$myguess" ]; do read -p "Enter your guess between 1-5: " yourguess done echo "$yourguess was right"

This version has no clues. != compares text, so 03 doesn't count as right.

Going further: Count the guesses. Set tries=0 before the loop, add 1 to it inside the loop, and print You took 3 tries at the end.


Part 2: Work through a list with for

A for loop runs its body once for each item in a list. You don't need a counter, and you don't need a test: the loop stops when the list runs out.

A for loop in a script

cp ~/scripts/shell/template.sh letter-loop.sh vim letter-loop.sh
for letter in a b c; do echo "I found letter $letter" done
Part What it does
for letter in a b c The list is a b c. Each time round, letter is set to the next item.
do ... done The body, the same as in a while loop.
$letter The current item: a, then b, then c.
chmod u+x letter-loop.sh ./letter-loop.sh
I found letter a I found letter b I found letter c

A for loop at the prompt

A loop works at the prompt too, on one line, the way you ran one in Lab 21. Put a ; where the script had a new line:

for letter in a b c; do echo "I found letter $letter"; done

The output is the same.

for loop in a script and at the prompt

Note: The screenshot was taken on an older server, where the script was called forloop.sh. The output is the same.

Make some files with one loop

Bash can build a list for you. {1..3} is brace expansion: bash turns it into 1 2 3 before the command runs. Try it:

echo file{1..3}.txt
file1.txt file2.txt file3.txt

To put some random words in each file, install the words package. It gives you a dictionary in /usr/share/dict/words, one word per line:

sudo dnf install -y words wc -l /usr/share/dict/words

shuf -n 5 picks 5 random lines from a file. One loop makes all three files:

for f in file{1..3}.txt; do shuf -n 5 /usr/share/dict/words > "$f"; done ls cat file1.txt
Part What it does
for f in file{1..3}.txt The list is file1.txt file2.txt file3.txt.
shuf -n 5 /usr/share/dict/words Prints 5 random words from the dictionary.
> "$f" Sends them into a file with the current name, from Lab 5. > creates the file if it doesn't exist.

Your words will be different, because they are random.

Loop over files

A wildcard makes a list as well. In Lab 5 you saw that the shell expands * before the command runs. It does the same in a for line.

cp ~/scripts/shell/template.sh file-info.sh vim file-info.sh
for file in file*.txt; do echo "$file" done
chmod u+x file-info.sh ./file-info.sh
file1.txt file2.txt file3.txt

Now change echo to cat in file-info.sh, and run it again.

Question: The loop and the list are the same. Why is the output so different?

Answer

$file holds a file name. echo "$file" prints the name. cat "$file" opens the file with that name and prints what is in it, so you see all 15 words. The loop gives you the name; the command decides what to do with it.

Task 3: Check several services at once

In Lab 19, Part 5, service-check.sh checked one service. A for loop can check a whole list.

Goal: Make services.sh. For each of nginx, sshd, chronyd, firewalld, docker and nftables, it prints a line such as nginx is running or nftables is NOT running.

Hint
Solution
cp ~/scripts/shell/template.sh services.sh vim services.sh
for service in nginx sshd chronyd firewalld docker nftables; do if systemctl is-active --quiet "$service"; then echo "$service is running" else echo "$service is NOT running" fi done
chmod u+x services.sh ./services.sh
nginx is running sshd is running chronyd is running firewalld is running docker is running nftables is NOT running

nftables has been stopped since Lab 14, when you went back to firewalld. Even with set -e, the script carries on after it, because a failed test inside if doesn't stop the script (Lab 19, Part 6).

Going further: Replace the six names with "$@", from Lab 11. Now the user chooses the list: ./services.sh nginx docker.


Part 3: A simple option with shift

Many commands take options, such as -a in ls -a. An option is an argument that starts with -. Your scripts can take them too.

Check for -a

cp ~/scripts/shell/template.sh options.sh vim options.sh
if [ "${1:-}" = "-a" ]; then option=TRUE shift else option=FALSE fi echo "Value for option is: $option" echo "Arguments left: $#. They are: $*"
Part What it does
"${1:-}" The first argument, or nothing if there isn't one. You used it in Lab 19, Part 7. With set -u, a plain "$1" would stop the script when it has no arguments.
shift Throws away $1 and moves every argument down one place: $2 becomes $1, $3 becomes $2, and $# goes down by 1.

Run it four ways:

chmod u+x options.sh ./options.sh ./options.sh -a ./options.sh -a one two ./options.sh one -a
Value for option is: FALSE Arguments left: 0. They are: Value for option is: TRUE Arguments left: 0. They are: Value for option is: TRUE Arguments left: 2. They are: one two Value for option is: FALSE Arguments left: 2. They are: one -a

shift removed -a, so the rest of the script only sees the other arguments. The last run shows the limit of this way of doing it: the script only looks at $1, so -a must come first.

Task 4: List files two ways

Goal: Make file-listings.sh. With no option, it prints Normal mode. and lists only the file names in the current directory. With -a, it prints Verbose mode. and lists all files, including hidden ones, in a long listing with human-readable sizes, sorted by time, with the newest last. Run it both ways.

Hint
Solution
cp options.sh file-listings.sh vim file-listings.sh
if [ "${1:-}" = "-a" ]; then option=TRUE shift else option=FALSE fi if [ "$option" = "TRUE" ]; then echo "Verbose mode." ls -larth else echo "Normal mode." ls fi
./file-listings.sh ./file-listings.sh -a
Option Means
-l Long listing: permissions, owner, size, date.
-a All files, including hidden ones such as . and ...
-r Reverse the order.
-t Sort by time, newest first. With -r, newest last.
-h Human-readable sizes, such as 4.0K.

With -a, the newest file is at the bottom, just above your prompt.


Part 4: Several options with getopts

options.sh checks one option, and only in the first place. Real commands take several options, in any order, and some options take a value, such as ssh -p 2222. Writing all of that with if and shift gets long. getopts is a bash command made for this job.

getopts works with case, a new statement that is a tidy way to write a long if / elif chain that tests one variable.

A getopts example

cp ~/scripts/shell/template.sh getopts-demo.sh vim getopts-demo.sh
while getopts ":ab:" option; do case "$option" in a) echo "Option -a was given" ;; b) echo "Option -b was given with the value: $OPTARG" ;; \?) echo "Error: unknown option -$OPTARG" >&2 exit 1 ;; :) echo "Error: option -$OPTARG needs a value" >&2 exit 1 ;; esac done echo "Finished reading the options."
Part What it does
getopts ":ab:" option Reads the next option into option. It returns a non-zero exit status when there are no options left, which ends the while loop.
ab: The options this script knows: -a and -b. The : after b means -b needs a value, such as -b hello.
: at the start Tells getopts not to print its own error messages. The script prints its own, in the last two branches.
$OPTARG The value given to an option that needs one. In the error branches, it holds the option letter that was wrong.
case "$option" in ... esac Compares $option with each pattern in turn. esac is case backwards, like fi and if.
a) A pattern. If $option is a, run the lines down to ;;.
;; Ends a branch. The script carries on after esac.
\?) getopts sets option to ? for an option it doesn't know. The \ is needed because a plain ? in a pattern is a wildcard that matches any one character.
:) getopts sets option to : when an option is missing its value.
>&2 Sends the error message to standard error, file descriptor 2, from Lab 5, where error messages belong.

Run it with good and bad options:

chmod u+x getopts-demo.sh ./getopts-demo.sh -a ./getopts-demo.sh -b hello ./getopts-demo.sh -a -b hello ./getopts-demo.sh -ab hello ./getopts-demo.sh -x echo $? ./getopts-demo.sh -b
Option -a was given Finished reading the options. Option -b was given with the value: hello Finished reading the options. Option -a was given Option -b was given with the value: hello Finished reading the options. Option -a was given Option -b was given with the value: hello Finished reading the options. Error: unknown option -x 1 Error: option -b needs a value

-a -b hello and -ab hello give the same result. getopts splits joined options for you, the way ls -la is the same as ls -l -a.

Note: getopts stops at the first argument that doesn't start with -. Put the options first: ./getopts-demo.sh -a word, not ./getopts-demo.sh word -a.

Task 5: Finish the user report

user-mgr.sh prints details about a user. It takes four options:

Option Prints
-u username Which user to report on. Required.
-n The user's full name.
-s The user's login shell.
-g The groups the user is in.

-u and -n work. -s and -g still print add logic here.

cp ~/scripts/shell/template.sh user-mgr.sh vim user-mgr.sh
# Settings, changed by the options user="" name="N" shell="N" group="N" # Read the options while getopts ":u:nsg" option; do case "$option" in u) user="$OPTARG" ;; n) name="Y" ;; s) shell="Y" ;; g) group="Y" ;; \?) echo "Error: unknown option -$OPTARG" >&2 echo "Usage: $0 -u username [-n] [-s] [-g]" >&2 exit 1 ;; :) echo "Error: option -$OPTARG needs a username" >&2 echo "Usage: $0 -u username [-n] [-s] [-g]" >&2 exit 1 ;; esac done # A username is required if [ -z "$user" ]; then echo "Error: give a username with -u" >&2 echo "Usage: $0 -u username [-n] [-s] [-g]" >&2 exit 1 fi # The user must exist if ! id "$user" &> /dev/null; then echo "Error: user $user does not exist on this system" >&2 exit 1 fi # Always show the last login echo "Last login for $user:" last -n 1 "$user" | head -n 1 # Full name if [ "$name" = "Y" ]; then full_name=$(getent passwd "$user" | cut -d: -f5) echo "Full name: $full_name" fi # Login shell if [ "$shell" = "Y" ]; then user_shell="add logic here" echo "Login shell: $user_shell" fi # Group membership if [ "$group" = "Y" ]; then user_groups="add logic here" echo "Groups: $user_groups" fi
Part What it does
":u:nsg" Four options. Only -u needs a value.
user="", name="N" ... Starting values. Each option changes one of them. With set -u, every variable needs a value before it is used.
[ -z "$user" ] True if $user is empty (zero length), so -u wasn't given.
if ! id "$user" &> /dev/null From Lab 19, Task 5: true if the user does not exist.
last -n 1 "$user" Shows the user's most recent login, from the login records in /var/log/wtmp. head -n 1 keeps the first line. If the user has never logged in, the line is empty.
getent passwd "$user" Prints the user's line from /etc/passwd, like grep "^$user:" /etc/passwd from Lab 3.
cut -d: -f5 The 5th field, the comment, which holds the full name. You set it for dritchie with useradd -c in Lab 2.

Test the parts that work, and the errors:

chmod u+x user-mgr.sh ./user-mgr.sh -u dritchie -n ./user-mgr.sh -n ./user-mgr.sh -u nosuchuser ./user-mgr.sh -u
Last login for dritchie: Full name: Dennis Ritchie Error: give a username with -u Usage: ./user-mgr.sh -u username [-n] [-s] [-g] Error: user nosuchuser does not exist on this system Error: option -u needs a username Usage: ./user-mgr.sh -u username [-n] [-s] [-g]

Your last-login line may show a login for dritchie, if they logged in during Lab 2.

Goal: Replace the two "add logic here" values, so that -s prints the user's login shell and -g prints the groups the user is in. Test it with your own user and with dritchie.

Hint
Solution
# Login shell if [ "$shell" = "Y" ]; then user_shell=$(getent passwd "$user" | cut -d: -f7) echo "Login shell: $user_shell" fi # Group membership if [ "$group" = "Y" ]; then user_groups=$(id -nG "$user") echo "Groups: $user_groups" fi
./user-mgr.sh -u angus -n -s -g ./user-mgr.sh -u dritchie -sg
Last login for angus: angus pts/0 192.168.64.1 Thu Nov 19 10:02 still logged in Full name: Angus Login shell: /bin/bash Groups: angus wheel research docker Last login for dritchie: Login shell: /bin/bash Groups: dritchie admin
Command What it does
cut -d: -f7 The 7th field of the /etc/passwd line: the login shell.
id -nG "$user" -G lists all the user's groups, and -n prints their names instead of numbers.

Your full name, groups and login line will be different. You are in research from Lab 6 and docker from Lab 21. dritchie is in admin from Lab 2.

Another way: groups "$user" also lists the groups, but it starts the line with the user's name and a colon: dritchie : dritchie admin.

Going further: Add a -h option that prints the usage line and exits with status 0, as your help block did in Lab 19. Add h to the option string, and an h) branch to the case.


Part 5: Debug a script with -x and -v

When a script doesn't do what you expect, you can add echo lines to see what is going on. Bash can do better: it can show you every command as it runs, with the variables already filled in.

Option Name What bash prints
-x xtrace Each command after expansion, just before it runs, with + in front. You see the real values of the variables.
-v verbose Each line exactly as it is written in the file, as bash reads it.

Both print to standard error, so they don't mix with what the script sends to standard output.

Trace a whole script with bash -x

Run count.sh from Part 1 with bash -x:

bash -x count.sh
+ set -euo pipefail + count=1 + '[' 1 -le 5 ']' + echo 'Count is 1' Count is 1 + count=2 + '[' 2 -le 5 ']' + echo 'Count is 2' Count is 2 ... + count=6 + '[' 6 -le 5 ']' + echo 'Done. count is now 6' Done. count is now 6

The lines with + are the trace. You see each test with the real numbers in it, so you can see exactly when [ 6 -le 5 ] stopped the loop. Lines without + are the script's normal output.

You can switch tracing on in three ways:

Way Traces
bash -x script.sh The whole script, this time only. Nothing in the file changes.
#!/bin/bash -x The whole script, every time it is run as ./script.sh. You add -x to the end of the first line.
set -x ... set +x Only the lines between them. - switches an option on, + switches it off.

-v works the same three ways: bash -v, #!/bin/bash -v, and set -v ... set +v. You can use both at once: bash -xv.

Tip: The trace goes to standard error, so > doesn't catch it. To save a long trace and read it with less, use 2>, from Lab 5: bash -x count.sh 2> trace.txt.

Switch debugging on for part of a script

cp ~/scripts/shell/template.sh debug-test.sh vim debug-test.sh
echo "--- Start of script ---" echo "Verbose and trace are OFF." sleep 2 echo "" echo "Switching ON set -v (verbose): bash prints each line as it reads it." set -v # This comment is printed too, because set -v prints every line it reads demo_v="Verbose mode is on" echo "The value of demo_v is: $demo_v" set +v echo "" echo "Back to normal. The lines above were printed as they are written in the file." sleep 2 echo "" echo "Switching ON set -x (trace): bash prints each command after expansion." set -x demo_x="Trace mode is on" echo "The value of demo_x is: $demo_x" set +x echo "" echo "Back to normal." echo "--- End of script ---"
chmod u+x debug-test.sh ./debug-test.sh
--- Start of script --- Verbose and trace are OFF. Switching ON set -v (verbose): bash prints each line as it reads it. # This comment is printed too, because set -v prints every line it reads demo_v="Verbose mode is on" echo "The value of demo_v is: $demo_v" The value of demo_v is: Verbose mode is on set +v Back to normal. The lines above were printed as they are written in the file. Switching ON set -x (trace): bash prints each command after expansion. + demo_x='Trace mode is on' + echo 'The value of demo_x is: Trace mode is on' The value of demo_x is: Trace mode is on + set +x Back to normal. --- End of script ---

Compare the two echo lines. -v shows $demo_v, as it is written. -x shows Trace mode is on, the value bash really used. That is why -x is usually the more useful one for finding a mistake.

set +v and set +x show up in their own output, because the option is still on when bash reads that line.

Task 6: Find the missing number

countdown.sh should count down from 5 to 1, then print Liftoff!.

cp ~/scripts/shell/template.sh countdown.sh vim countdown.sh
count=5 while [ "$count" -gt 1 ]; do echo "$count..." count=$(( count - 1 )) sleep 1 done echo "Liftoff!"
chmod u+x countdown.sh ./countdown.sh
5... 4... 3... 2... Liftoff!

1 is missing.

Goal: Run countdown.sh with tracing on, find the line that stops the loop too early, and fix it so the countdown includes 1.

Hint
Solution
bash -x countdown.sh
... + echo 2... 2... + count=1 + sleep 1 + '[' 1 -gt 1 ']' + echo 'Liftoff!' Liftoff!

When count is 1, the test is [ 1 -gt 1 ]. 1 is not greater than 1, so the test is false and the loop stops before it prints 1.... Change the test so that 1 still passes:

while [ "$count" -gt 0 ]; do

[ "$count" -ge 1 ] works too. Run it again:

./countdown.sh
5... 4... 3... 2... 1... Liftoff!

This kind of mistake, where a loop runs one time too many or one time too few, is so common that programmers have a name for it: an off-by-one error. The trace shows the real numbers in the test, which makes it easy to spot.

Going further: Write the countdown as a for loop instead. {5..1} counts down.


Part 6: Save your scripts in GitLab

As in Lab 19, Part 8, your scripts belong in your GitLab repository.

Task 7: Push your scripts

Goal: Copy every .sh file from ~/inclass/lab-22 to a new scripts/lab-22 folder in your itfdn-140-inclass-$USER repository. Commit and push them, and check in GitLab that they are there. Stop your agent when you have finished.

Hint
Solution
eval "$(ssh-agent -s)" ssh-add cd ~/git/gitlab/itfdn-140-inclass-$USER git pull mkdir -p scripts/lab-22 cp ~/inclass/lab-22/*.sh scripts/lab-22/ ls -l scripts/lab-22 git add scripts/lab-22 git commit -m "add lab 22 loop, option and debugging scripts" git push eval "$(ssh-agent -k)"

ls -l shows the scripts kept their execute permission, so Git records them as mode 100755, as in Lab 11.

If you changed the help block in your template in Before you start, copy it to scripts/shell/ and push it too, as in Lab 19, Task 8.


Lab summary

You have now:

Questions to consider

Discuss these with others in class:

  1. When would you choose a while loop, and when a for loop?
  2. In date.sh, why did the time stay the same before you moved the date line into the loop?
  3. What happens to a while loop if nothing in its body changes the value it tests? How do you get out of it?
  4. options.sh only sees -a when it comes first. What does getopts do better?
  5. Why should a script send its error messages to standard error, not standard output?
  6. When is bash -x more useful than adding echo lines to a script?
  7. Which checks from earlier labs, such as pinging several servers or checking several services, could a for loop do for you?

Troubleshooting

Q. My loop never ends.

A. Press Ctrl+C. Then check that something in the body changes the value the test looks at, such as count=$(( count + 1 )). A while true loop needs a break that can be reached.

Q. I get "syntax error near unexpected token `done'".

A. The do is missing, or, on one line at the prompt, a ; is missing. The pattern is for x in a b c; do ...; done and while [ test ]; do ...; done.

Q. My script stops after the first time round the loop, with no error.

A. You may have written (( count++ )) or (( count = count + 1 )) on its own line. When the result is 0, that command has exit status 1, and set -e stops the script. Use count=$(( count + 1 )), as in this lab.

Q. I get "integer expression expected".

A. A guess or a counter that isn't a number reached -lt, -gt or -le, as in Lab 19. Type a number, and check that the variable was set before the loop.

Q. shuf says "/usr/share/dict/words: No such file or directory".

A. The words package isn't installed. Run sudo dnf install -y words.

Q. ./options.sh says "$1: unbound variable".

A. The script uses "$1". With set -u, that fails when there are no arguments. Write "${1:-}".

Q. Every option to my getopts script says "unknown option".

A. The case has ?) without the backslash. A plain ? matches any one character, so it catches every option before the right branch is reached. Write \?).

Q. user-mgr.sh dritchie -n says "give a username with -u".

A. getopts stops at the first argument that doesn't start with -, and the username needs -u in front of it. Run ./user-mgr.sh -u dritchie -n.

Q. I get "syntax error near unexpected token )'" in a case`.

A. A branch is missing its ;;, or the case is missing its esac. Each branch ends with ;;.

Q. bash -x script.sh > trace.txt leaves the trace on my screen.

A. The trace goes to standard error. Use 2> trace.txt, or &> trace.txt to save both, as in Lab 5.

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