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: readonly keeps a shell script from changing an important path by accident

Shell
~/tips/tip-shell-readonly-constants

readonly BACKUP_DIR=/srv/backup

Lock a variable after you set it, so later code cannot overwrite it.

In a long script, a variable set at the top can be overwritten fifty lines further down by a loop that reuses the name. For paths that a script deletes from, I want that to be impossible.

Mark the variable as read-only when you set it:

readonly BACKUP_DIR=/srv/backup
readonly KEEP_DAYS=14

BACKUP_DIR=/  # bash: BACKUP_DIR: readonly variable

Any later assignment fails with an error, and the value stays what it was. unset BACKUP_DIR is refused too. Combine it with set -e and the script stops at the bad line instead of carrying on.

declare -r does the same in bash. Without a value, readonly NAME locks a variable that already exists, which is handy for something read from a config file:

source ./backup.conf
readonly BACKUP_DIR KEEP_DAYS

The lock lasts for the life of the shell, with no way to undo it. That is fine in a script, but if you try it in your interactive terminal, the variable stays stuck until you close the window. A function that uses local with the same name also cannot shadow it, so pick names that are clearly meant as constants, like the uppercase ones above.

Further reading: Bash manual: Bourne Shell Builtins (readonly)

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