Readonly variables and declare
What you need to know
Use readonly name=value to prevent a variable from being reassigned or unset in the current shell. The declare builtin can show or set variable attributes. An attribute is a property that affects how Bash treats a variable. declare -p name prints its declaration, not just its value. Here we focus on scalar variables; array and function attributes come later.
Run each example separately as a new Bash script (Chapter 1). Tested with Bash 5.2.37 on Debian 13, default shell options; no personal configuration is required.
Inspect an ordinary variable
Expected stdout:
declare -- mode="demo"The declaration shows the name and value. The exact formatting can vary between Bash versions.
Mark a setting readonly
readonly app_name='ByteMind'printf '%s\n' "$app_name"declare -p app_nameExpected stdout:
ByteMinddeclare -r app_name="ByteMind"The -r attribute indicates readonly. It protects the variable within this shell, not a file or external service.
Observe an attempted reassignment safely
bash -c 'readonly mode=demo; mode=live'printf 'status=%s\n' "$?"Expected stdout:
status=1The child shell reports an error on stderr and exits nonzero on the tested version. The surrounding shell can still print the status.
Common mistakes
readonly is not a security boundary and does not make a value secret. You cannot simply undo readonly with unset. Practice in fresh Bash processes to avoid leaving readonly names in your interactive shell.
Practice
In a fresh Bash process define release=demo, inspect it, mark it readonly and explain why reassignment fails.
Next lesson: Export and environment inheritance