Read-Only Variables with readonly
A read-only variable is a variable whose value can no longer be changed or removed once it has been set. Bash provides the readonly built-in command for this. It is the closest thing Bash has to a constant, and it protects important values, such as a version number or a limit, from being overwritten by a typing mistake or by another part of the script.
Syntax
readonly NAME=value # create a read-only variable
readonly NAME # make an existing variable read-only
readonly -p # list all read-only variables
readonly -a NAME=(...) # a read-only indexed array
readonly -f function # make a function read-only
declare -r NAME=value does the same as readonly NAME=value. The -r stands for "read-only".
Creating and Using a Read-Only Variable
A read-only variable can be read as often as you like:
readonly MAX=5
echo "MAX=$MAX"
MAX=5
Use declare -p or readonly -p to see the attribute. The -r in the output is the read-only flag:
declare -r NAME=fixed
declare -p NAME
declare -r NAME="fixed"
What Happens When You Change One
An assignment to a read-only variable fails with an error message and a non-zero exit status, and the value stays the same:
cat > ro1.sh <<'EOF'
readonly MAX=5
MAX=6
echo "after the failed assignment, MAX=$MAX"
EOF
bash ro1.sh
ro1.sh: line 2: MAX: readonly variable
after the failed assignment, MAX=5
The failed assignment on line 2 returned status 1, but the script went on to the next line and MAX was still 5. In this test, Bash 5.2 did not stop a script just because of that error. The script continues unless something else stops it.
Two situations behave differently:
- With
set -eenabled (a later lesson covers it), the failed assignment ends the script with status 1. - Inside a function body, a failed assignment abandoned the rest of that function in Bash 5.2.21, and the script continued after the function call.
Do not depend on the script carrying on after an assignment error. The safest approach is to avoid assigning to a read-only name at all.
Making an Existing Variable Read-Only
You can assign a value first and lock it afterward:
cat > ro5.sh <<'EOF'
X=first
readonly X
X=second
echo "X=$X"
EOF
bash ro5.sh
ro5.sh: line 3: X: readonly variable
X=first
The variable kept its first value, and the second assignment was refused.
Read-Only Variables Cannot Be Unset
The unset command, which removes variables, is also refused:
cat > ro2.sh <<'EOF'
readonly LIMIT=10
unset LIMIT
echo "status=$?"
echo "LIMIT=$LIMIT"
EOF
bash ro2.sh
ro2.sh: line 2: unset: LIMIT: cannot unset: readonly variable
status=1
LIMIT=10
Once a variable is read-only, it stays in place and keeps its value for the rest of that shell's life. There is no command that removes the attribute. If you need a variable that you can change, do not make it read-only. A later lesson covers unset for ordinary variables.
Read-Only Variables in Scripts
Constants at the top of a script are the most common use. The script below sets two constants and then tries to change one of them by accident:
cat > retry.sh <<'EOF'
#!/usr/bin/env bash
readonly APP_NAME="backup-tool"
readonly MAX_RETRIES=3
attempt=1
while (( attempt <= MAX_RETRIES )); do
echo "$APP_NAME: attempt $attempt of $MAX_RETRIES"
(( attempt++ ))
done
MAX_RETRIES=5
echo "after: $MAX_RETRIES"
EOF
bash retry.sh
backup-tool: attempt 1 of 3
backup-tool: attempt 2 of 3
backup-tool: attempt 3 of 3
retry.sh: line 9: MAX_RETRIES: readonly variable
after: 3
The loop used the constants normally. The attempted change on line 9 was refused and printed a message that names the line and the variable, so the mistake is easy to find. Without readonly, the script would have silently changed the limit.
Uppercase names for read-only variables follow the same convention as for constants and environment variables.
Read-Only and Local Variables in Functions
A function cannot create a local variable with the name of a read-only variable. The local command fails, and the function continues to see the global one:
cat > ro6.sh <<'EOF'
readonly G=global
f() { local G=inner; echo "inside: $G"; }
f
echo "outside: $G"
EOF
bash ro6.sh
ro6.sh: line 2: local: G: readonly variable
inside: global
outside: global
This means a read-only variable cannot be shadowed. It keeps its value everywhere in the shell.
Read-Only Arrays
The -a option creates a read-only indexed array. Both changes to the whole array and changes to single elements are refused:
cat > ro7.sh <<'EOF'
readonly -a LIST=(a b c)
LIST+=(d)
echo "append status=$?"
echo "${LIST[@]}"
LIST[0]=z
echo "${LIST[@]}"
EOF
bash ro7.sh
ro7.sh: line 2: LIST: readonly variable
append status=1
a b c
ro7.sh: line 5: LIST: readonly variable
a b c
Both attempts failed, and the array still holds a b c.
Read-Only Functions
The -f option applies the same protection to a function, so a later definition cannot replace it:
cat > ro9.sh <<'EOF'
hi() { echo hi; }
readonly -f hi
hi() { echo bye; }
echo "status=$?"
hi
EOF
bash ro9.sh
ro9.sh: line 3: hi: readonly function
status=1
hi
Read-Only Does Not Pass to Child Processes
The read-only attribute belongs to the shell where you set it. A variable that is both exported and read-only gives its value to children, but the child gets an ordinary variable that it is free to change:
cat > ro8.sh <<'EOF'
export LIMIT_DEMO=1
readonly LIMIT_DEMO
bash -c 'LIMIT_DEMO=2; echo "child changed its own copy: $LIMIT_DEMO"; readonly -p | grep -c LIMIT_DEMO'
echo "parent still has: $LIMIT_DEMO"
EOF
bash ro8.sh
child changed its own copy: 2
0
parent still has: 1
The count of 0 from grep -c shows that the child did not receive the read-only attribute. Protection from readonly therefore applies only inside the process that declared it. It does not protect values across the programs that your script starts.
Sourcing a File That Defines Constants Twice
A shared file of constants is easy to load twice by accident, for example when two scripts both source it. The second load tries to assign to a variable that is already read-only:
printf 'readonly VERSION=1.0\n' > consts.sh
cat > ro16.sh <<'EOF'
source ./consts.sh
source ./consts.sh
echo "second source status=$?"
echo "VERSION=$VERSION"
EOF
bash ro16.sh
./consts.sh: line 1: VERSION: readonly variable
second source status=1
VERSION=1.0
The second load reported an error and returned status 1. A guard avoids this. The test [[ -v NAME ]] is true when the variable is set, so the assignment runs only the first time:
printf '[[ -v VERSION2 ]] || readonly VERSION2=2.0\n' > consts2.sh
cat > ro17.sh <<'EOF'
source ./consts2.sh
source ./consts2.sh
echo "second source status=$? VERSION2=$VERSION2"
EOF
bash ro17.sh
second source status=0 VERSION2=2.0
The || operator runs the right side only when the left side fails, so the second load skips the assignment and finishes with status 0.
Subshells Inherit the Protection
A subshell is a copy of the shell, so a read-only variable stays read-only inside it:
cat > ro18.sh <<'EOF'
readonly K=1
( unset K; echo "in subshell K=$K" )
echo "outer K=$K"
EOF
bash ro18.sh
ro18.sh: line 2: unset: K: cannot unset: readonly variable
in subshell K=1
outer K=1
Built-In Read-Only Variables
Bash itself marks a few of its own variables read-only. UID, the numeric id of the current user, is the usual example, and assigning to it fails with UID: readonly variable, as lesson 35 mentioned. Your own read-only variables behave in exactly the same way.
Listing Read-Only Variables
readonly -p prints every read-only variable in a form that can be pasted back into a script. Filter it to see only your own:
cat > ro4.sh <<'EOF'
readonly A=1 B=2
readonly -p | grep -E ' (A|B)='
EOF
bash ro4.sh
declare -r A="1"
declare -r B="2"
A real shell lists several built-in read-only variables as well, such as UID, so the filter keeps the output short.