Read-Only Variables with readonly

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 40 of 205

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 -e enabled (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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Read-Only Variables with readonly and get answers drawn from it.

Signed-in readers only.