0
0
Bash Scriptingscripting~15 mins

Read-only variables (readonly) in Bash Scripting - Deep Dive

Choose your learning style9 modes available
Overview - Read-only variables (readonly)
What is it?
Read-only variables in bash are variables that cannot be changed once set. Using the readonly command, you can mark a variable so that any attempt to modify it later causes an error. This helps protect important values from accidental changes during script execution. It is a simple way to make your scripts safer and more predictable.
Why it matters
Without read-only variables, scripts can accidentally overwrite important data, causing bugs or unexpected behavior. Imagine writing a recipe and someone changing the amount of salt halfway through cooking—that could ruin the dish. Read-only variables prevent such mistakes by locking values in place, making scripts more reliable and easier to debug.
Where it fits
Before learning about read-only variables, you should understand how to create and use variables in bash. After mastering read-only variables, you can explore more advanced bash features like arrays, functions, and environment variables to write more powerful scripts.
Mental Model
Core Idea
A read-only variable is like a locked box: once you put something inside, you cannot change it until you unlock or remove the lock.
Think of it like...
Think of a read-only variable as a sealed envelope containing a message. Once sealed, you cannot change the message inside without breaking the seal, which bash prevents by throwing an error.
┌───────────────┐
│ Variable name │
├───────────────┤
│   Value       │
├───────────────┤
│  [LOCKED]     │
└───────────────┘

Trying to change value → ERROR
Build-Up - 6 Steps
1
FoundationCreating and Using Variables
🤔
Concept: How to create and assign values to variables in bash.
In bash, you create a variable by writing its name followed by an equal sign and the value, without spaces. For example: MY_VAR="Hello" you can then use it by prefixing with a dollar sign: echo $MY_VAR This prints the value stored in MY_VAR.
Result
Hello
Understanding how to create and use variables is the first step to managing data in scripts.
2
FoundationChanging Variable Values
🤔
Concept: Variables in bash can be changed anytime by assigning a new value.
You can overwrite a variable by assigning a new value: MY_VAR="Hello" MY_VAR="World" echo $MY_VAR This will print 'World' because the original value was replaced.
Result
World
Knowing that variables are mutable by default helps you realize why accidental changes can cause bugs.
3
IntermediateMaking Variables Read-Only
🤔Before reading on: do you think marking a variable readonly allows you to change it later? Commit to yes or no.
Concept: Using the readonly command to lock a variable's value so it cannot be changed.
To make a variable read-only, use the readonly command: MY_VAR="Hello" readonly MY_VAR Now, if you try to change MY_VAR: MY_VAR="World" bash will show an error: bash: MY_VAR: readonly variable
Result
bash: MY_VAR: readonly variable
Understanding that readonly prevents changes protects critical data and prevents accidental bugs.
4
IntermediateReadonly Variables and Exported Variables
🤔Before reading on: do you think readonly variables can be exported to child processes? Commit to yes or no.
Concept: Readonly variables can be exported to child processes, but readonly applies only in the current shell.
You can export a readonly variable so child scripts see it: MY_VAR="Hello" readonly MY_VAR export MY_VAR Child scripts can read MY_VAR but cannot change it in the parent shell. However, child shells can override it locally unless they also mark it readonly.
Result
Child process sees MY_VAR as 'Hello', but parent's readonly protection stays intact.
Knowing the scope of readonly helps avoid confusion about variable behavior across processes.
5
AdvancedReadonly Arrays and Limitations
🤔Before reading on: do you think readonly prevents changing elements inside an array variable? Commit to yes or no.
Concept: Readonly applies to the variable name, not the contents of complex types like arrays.
If you make an array readonly: readonly MY_ARRAY You cannot reassign MY_ARRAY to a new array, but you can still change individual elements: MY_ARRAY[0]=42 This works because readonly locks the variable name, not the data inside.
Result
Elements inside the array can still be changed despite readonly on the array variable.
Understanding this subtlety prevents false assumptions about data immutability in bash.
6
ExpertReadonly Variables and Script Security
🤔Before reading on: do you think readonly variables fully secure sensitive data in bash scripts? Commit to yes or no.
Concept: Readonly variables improve script safety but do not provide security against malicious users or processes.
Readonly variables prevent accidental changes but do not encrypt or hide data. Anyone with access to the script or environment can read or override variables in child shells. For true security, use system permissions and encryption methods outside bash readonly.
Result
Readonly helps prevent bugs but is not a security feature.
Knowing the limits of readonly prevents overreliance and encourages proper security practices.
Under the Hood
When you mark a variable readonly, bash sets an internal flag on the variable's entry in its symbol table. This flag tells the shell to reject any future assignment attempts to that variable name. The shell checks this flag every time an assignment is made and raises an error if the variable is locked. However, for arrays or complex types, the flag applies only to the variable name, not to the contents, so element changes bypass the readonly check.
Why designed this way?
Readonly variables were introduced to help script authors prevent accidental overwrites of important data without adding complex immutability features. Bash prioritizes simplicity and performance, so readonly is a lightweight flag rather than a full data protection system. Alternatives like constant variables in other languages are more complex and were not suitable for bash's design goals.
┌───────────────┐
│ Variable Table│
├───────────────┤
│ MY_VAR        │
│ Value: Hello  │
│ Readonly: Yes │
└───────────────┘

Assignment attempt → Check readonly flag → If yes → Error

If no → Update value
Myth Busters - 3 Common Misconceptions
Quick: Does readonly prevent changing elements inside an array variable? Commit to yes or no.
Common Belief:Readonly makes the entire variable and its contents completely unchangeable.
Tap to reveal reality
Reality:Readonly only locks the variable name; array elements can still be modified.
Why it matters:Assuming full immutability can lead to bugs when array elements change unexpectedly.
Quick: Can readonly variables be changed in child processes? Commit to yes or no.
Common Belief:Readonly variables cannot be changed anywhere once set.
Tap to reveal reality
Reality:Readonly applies only in the current shell; child processes can override unless they also mark variables readonly.
Why it matters:Misunderstanding scope can cause unexpected behavior in scripts using child processes.
Quick: Does readonly protect sensitive data from being read by others? Commit to yes or no.
Common Belief:Readonly variables secure data from unauthorized access.
Tap to reveal reality
Reality:Readonly only prevents changes, not reading or external access.
Why it matters:Relying on readonly for security can expose sensitive information.
Expert Zone
1
Readonly variables do not prevent unset operations; you cannot unset a readonly variable without restarting the shell.
2
Readonly variables can be declared at the time of assignment or after; declaring readonly before assignment causes an error.
3
Readonly variables interact subtly with shell options like 'set -u' (nounset), affecting error handling when variables are unset.
When NOT to use
Avoid readonly when you need variables to change dynamically during script execution. For complex data protection, use external tools or languages with stronger immutability features like Python or Rust.
Production Patterns
In production scripts, readonly is used to lock configuration values, constants, or environment settings early in the script to prevent accidental overwrites. It is common to combine readonly with export for environment variables that should not change during runtime.
Connections
Immutable Data Structures
Readonly variables are a simple form of immutability similar to immutable data structures in programming languages.
Understanding readonly helps grasp the broader concept of immutability, which improves reliability and predictability in software.
File Permissions
Readonly variables conceptually resemble read-only file permissions that prevent modification of files.
Knowing how file permissions work clarifies why locking variables prevents changes but not reading.
Legal Contracts
Readonly variables are like signed contracts that cannot be changed without agreement.
This connection shows how locking agreements in law parallels locking data in scripts to prevent accidental changes.
Common Pitfalls
#1Trying to change a readonly variable causes script errors.
Wrong approach:MY_VAR="Hello" readonly MY_VAR MY_VAR="World"
Correct approach:MY_VAR="Hello" # Do not reassign MY_VAR after readonly # Use a different variable if needed NEW_VAR="World"
Root cause:Misunderstanding that readonly variables cannot be reassigned once locked.
#2Assuming readonly protects array elements from modification.
Wrong approach:MY_ARRAY=(1 2 3) readonly MY_ARRAY MY_ARRAY[0]=42
Correct approach:MY_ARRAY=(1 2 3) readonly MY_ARRAY # To prevent changes, avoid modifying elements or use other languages
Root cause:Believing readonly applies to contents of complex variables, not just the variable name.
#3Expecting readonly variables to secure sensitive data from reading.
Wrong approach:PASSWORD="secret" readonly PASSWORD # Assume PASSWORD is secure from all access
Correct approach:# Use system permissions or encryption for security PASSWORD="secret" readonly PASSWORD
Root cause:Confusing immutability with security or privacy.
Key Takeaways
Readonly variables in bash lock a variable's value to prevent accidental changes during script execution.
Readonly applies only to the variable name, not to the contents of complex types like arrays.
Readonly variables improve script reliability but do not provide security against unauthorized reading or access.
Understanding the scope of readonly helps avoid confusion when working with child processes and exported variables.
Using readonly for constants and configuration values is a best practice to make scripts safer and easier to maintain.