Bird
Raised Fist0
Bash Scriptingscripting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the readonly command do in a bash script?
easy
A. It prints the value of a variable.
B. It deletes a variable from the script.
C. It makes a variable unchangeable after assignment.
D. It allows a variable to be changed multiple times.

Solution

  1. Step 1: Understand the purpose of readonly

    The readonly command is used to mark a variable so it cannot be changed later in the script.
  2. Step 2: Compare options with the command's function

    Only "It makes a variable unchangeable after assignment." correctly describes that the variable becomes unchangeable after assignment.
  3. Final Answer:

    It makes a variable unchangeable after assignment. -> Option C
  4. Quick Check:

    readonly = makes variable unchangeable [OK]
Hint: Readonly means variable cannot be changed after set [OK]
Common Mistakes:
  • Thinking readonly deletes the variable
  • Confusing readonly with printing variable
  • Assuming readonly allows changes
2. Which of the following is the correct syntax to make a variable MYVAR read-only in bash?
easy
A. readonly MYVAR =value
B. readonly MYVAR
C. MYVAR readonly
D. set readonly MYVAR

Solution

  1. Step 1: Recall the syntax of readonly

    The correct syntax is to first assign the variable, then use readonly MYVAR to make it read-only.
  2. Step 2: Analyze each option

    readonly MYVAR =value tries to assign and readonly together, which is invalid. readonly MYVAR correctly uses readonly MYVAR. Options C and D are not valid bash syntax.
  3. Final Answer:

    readonly MYVAR -> Option B
  4. Quick Check:

    Use readonly VAR after assignment [OK]
Hint: Assign first, then use readonly VAR to lock it [OK]
Common Mistakes:
  • Trying to assign value inside readonly command
  • Placing readonly after variable name
  • Using invalid commands like set readonly
3. What will be the output of this script?
MYVAR=hello
readonly MYVAR
MYVAR=world
echo $MYVAR
medium
A. world
B. Error: cannot modify readonly variable
C. Syntax error
D. hello

Solution

  1. Step 1: Understand the script flow

    The variable MYVAR is assigned "hello" and then made readonly. The script then tries to change it to "world".
  2. Step 2: Predict the behavior when modifying a readonly variable

    Bash will produce an error message when trying to assign a new value to a readonly variable, but the script will continue and the value of MYVAR remains "hello". The echo command outputs the original value.
  3. Final Answer:

    hello -> Option D
  4. Quick Check:

    Readonly variable value remains unchanged; echo prints original value [OK]
Hint: Changing readonly variable causes error message but value unchanged [OK]
Common Mistakes:
  • Assuming variable changes silently
  • Expecting syntax error instead of runtime error
  • Thinking echo prints new value
4. Identify the error in this script:
readonly MYVAR =10
MYVAR=20
echo $MYVAR
medium
A. Cannot assign value during readonly declaration
B. Variable name is invalid
C. Missing export keyword
D. No error, script runs fine

Solution

  1. Step 1: Check the syntax of readonly with assignment

    In bash, readonly cannot be combined with assignment like readonly MYVAR =10. The variable must be assigned first, then made readonly.
  2. Step 2: Analyze the error caused by this syntax

    This syntax causes an error because bash expects only variable names after readonly, not assignments.
  3. Final Answer:

    Cannot assign value during readonly declaration -> Option A
  4. Quick Check:

    Assign first, then readonly VAR separately [OK]
Hint: Assign before readonly; no assignment inside readonly [OK]
Common Mistakes:
  • Trying to assign value inside readonly command
  • Ignoring syntax error messages
  • Confusing export with readonly
5. You want to protect a variable CONFIG_PATH so it cannot be changed accidentally in your script, but you also want to print its value later. Which sequence of commands is correct?
hard
A. CONFIG_PATH=/etc/config readonly CONFIG_PATH echo $CONFIG_PATH
B. readonly CONFIG_PATH=/etc/config echo $CONFIG_PATH
C. CONFIG_PATH=/etc/config echo $CONFIG_PATH readonly CONFIG_PATH
D. echo $CONFIG_PATH CONFIG_PATH=/etc/config readonly CONFIG_PATH

Solution

  1. Step 1: Assign the variable before making it readonly

    You must first assign CONFIG_PATH a value, then use readonly to lock it.
  2. Step 2: Print the variable after it is readonly

    Printing the variable after making it readonly is valid and will show the assigned value.
  3. Final Answer:

    CONFIG_PATH=/etc/config readonly CONFIG_PATH echo $CONFIG_PATH -> Option A
  4. Quick Check:

    Assign, then readonly, then print [OK]
Hint: Assign first, readonly second, then use variable [OK]
Common Mistakes:
  • Trying to assign inside readonly
  • Printing variable before assignment
  • Making variable readonly before assignment
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard