Skip to main content
A read-only variable in Bash is an immutable identifier whose state—whether holding an assigned value or remaining explicitly unassigned—cannot be modified, reassigned, or unset for the duration of the shell session or script execution. Once the read-only attribute is applied, the Bash interpreter enforces strict immutability at the environment level.

Syntax and Initialization

Bash provides three primary built-in commands to apply the read-only attribute: readonly, declare -r, and typeset -r.
The read-only attribute can also be applied to an existing variable dynamically after its initial declaration:
Unassigned Read-only Variables If a variable is marked read-only without being assigned a value, it enters a permanently unset state. The variable cannot be assigned a value subsequently, locking it as an empty, immutable reference.
Arrays and Functions The read-only attribute extends beyond standard scalar variables. It can be applied to indexed arrays, associative arrays, and functions using specific flags:
  • -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 with set -e (exit on error).
  • Unsetting: The unset built-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 as local in that scope).
  • declare -r and typeset -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.
To propagate a read-only variable to the environment of child processes, it must be exported. The 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 the readonly 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