brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: set -u makes a script stop on a typo in a variable name

Shell
~/tips/tip-shell-set-u-nounset

set -u

Makes bash exit with an error instead of treating an unset variable as empty.

A misspelled variable in bash does not fail. It quietly becomes an empty string, and that is how a harmless-looking line turns into a nasty one.

set -u (also written set -o nounset) makes bash treat an expansion of an unset variable as an error. In a non-interactive shell that means the script exits. Put it near the top:

#!/usr/bin/env bash
set -u
target="/mnt/user/appdata/<app>"
echo "cleaning $targt"

Without -u that prints an empty name and carries on. With it, bash writes an error that targt is an unbound variable and stops. Now picture the same typo inside rm -rf "$targt/cache", which would turn into rm -rf "/cache". That is the case this option is for, and it costs one line.

Sometimes a variable may legitimately be empty, for example an optional argument. Give it a default with ${name:-} and bash is satisfied:

name="${1:-}"
if [ -z "$name" ]; then echo "usage: $0 name"; exit 1; fi

Without that default, $1 in a script started with no arguments would stop it with an unbound variable error before your own usage message gets a chance.

The manual says the special parameters @ and * are exempt, so "$@" with no arguments is fine. The option applies to the shell it is set in, so a sourced script or a function that relies on an unset variable will start failing once the caller turns it on.

Further reading: bash(1) manual page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link