What does `readonly` do and when do you use it?
BeginnerConceptVariables, quoting and expansions
Answer
It makes a variable (or function with readonly -f) immutable for the rest of the shell's life; assigning again fails with bash: X: readonly variable and, under set -e, exits. Use it for constants that must never change mid-script:
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly BACKUP_ROOT=/var/backups/opskit
Do not mark variables readonly in a library that might be sourced twice; the second source fails. Guard with [[ -v VAR ]] || readonly VAR=... or a load guard.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate