Syntax and Initialization
Bash provides three primary built-in commands to apply the read-only attribute:readonly, declare -r, and typeset -r.
unset state. The variable cannot be assigned a value subsequently, locking it as an empty, immutable reference.
-a: Indexed arrays-A: Associative arrays-f: Functions
Behavioral Mechanics
When an identifier possesses the read-only attribute, the Bash interpreter intercepts and blocks state-change operations.- Reassignment: Attempting to change the value triggers a standard error (
stderr), but does not halt script execution unless the shell is running withset -e(exit on error). - Unsetting: The
unsetbuilt-in explicitly fails when targeting a read-only variable.
Scope and Exporting
Read-only variables adhere to standard Bash dynamic scoping rules, but the initialization commands exhibit different default scoping behaviors when invoked inside functions:readonly: Creates a global variable by default, even when invoked inside a function (unless the variable was previously declared aslocalin that scope).declare -randtypeset -r: Automatically restrict the variable to the function’s local scope.local -r: Explicitly enforces local scoping for a read-only variable within a function.
readonly built-in does not support an export flag. To simultaneously export and mark a variable as read-only, use declare -rx (or typeset -rx), or apply the export and readonly commands sequentially.
Introspection
The Bash interpreter maintains an internal registry of all variables with the read-only attribute. To output a list of all currently defined read-only variables in the active shell session, invoke thereadonly command with the -p (print) flag.
By default, Bash formats this output using its specific extension syntax (declare -r), which is not POSIX-compliant. Bash only produces POSIX-compliant output (readonly VAR="value") if the shell is explicitly executed in POSIX mode (--posix).
Tired of Poor Bash Skills? Fix That With Deep Grasping!Learn More





