Interview Prep/Shell Scripting/Variables, quoting and expansions

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions