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
MediumMake a script that counts the different names in a sign-up list strict, and fix the bug that strictness reveals.
- Open
unique.sh. It takes the list file as its first argument. - Add
set -euo pipefailon its own line right after the comment. - Run
bash unique.sh signups.txt. Instead of a blank count,set -unow reports a variable name with a typo. Fix the typo so the last line printsUnique names: N. - Save the file. A missing list now stops the script with the
sorterror 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: 4Then 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 directoryTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground