Menu
CoddyTech

Unset Variables And Pipes

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 28 of 39.

set -u makes using a variable that was never set an error, so a typo stops the script instead of turning into an empty string.

#!/bin/bash
set -u
name="Ana"
echo "Hello, $nmae"

bash greet.sh prints greet.sh: line 4: nmae: unbound variable and exits with code 1. Without set -u it prints Hello, and exits with 0. A missing argument such as $1 counts too; write ${1:-guest} when an argument is optional.

A pipeline's exit code is normally its last command's. set -o pipefail makes the pipeline fail when any command in it fails.

#!/bin/bash
set -eo pipefail
cat orders.txt | wc -l
echo "counted"

With no orders.txt, this prints the cat error and 0, then stops with code 1. Without pipefail, wc succeeds, so counted prints as well. Most scripts turn on all three settings with one line under the shebang: set -euo pipefail.

challenge icon

Challenge

Medium

Make a script that counts the different names in a sign-up list strict, and fix the bug that strictness reveals.

  1. Open unique.sh. It takes the list file as its first argument.
  2. Add set -euo pipefail on its own line right after the comment.
  3. Run bash unique.sh signups.txt. Instead of a blank count, set -u now reports a variable name with a typo. Fix the typo so the last line prints Unique names: N.
  4. Save the file. A missing list now stops the script with the sort error and code 2, and no argument at all stops it with an unbound variable error and code 1.

Try it: run bash unique.sh signups.txt. It prints:

Unique names: 4

Then run bash unique.sh members.txt, a file that does not exist. It prints the error and nothing else:

sort: cannot read: members.txt: No such file or directory

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground