0
0
Bash Scriptingscripting~10 mins

Read-only variables (readonly) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Read-only variables (readonly)
Declare variable
Make variable readonly
Try to change variable
Error: cannot modify readonly variable
Use variable as is
End
You declare a variable, mark it readonly, then any attempt to change it causes an error, preserving its value.
Execution Sample
Bash Scripting
myvar="hello"
readonly myvar
myvar="world"
echo "$myvar"
This script sets a variable, makes it readonly, tries to change it (which fails), then prints the variable.
Execution Table
StepCommandActionVariable StateOutputNotes
1myvar="hello"Assign 'hello' to myvarmyvar='hello'Variable created with value 'hello'
2readonly myvarMake myvar readonlymyvar='hello' (readonly)myvar is now readonly
3myvar="world"Attempt to change myvarmyvar='hello' (readonly)bash: myvar: readonly variableError: cannot modify readonly variable
4echo "$myvar"Print myvar valuemyvar='hello' (readonly)helloValue remains unchanged
💡 Script ends after printing 'hello'; modification attempt failed due to readonly.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
myvarundefined'hello''hello' (readonly)'hello' (readonly)'hello' (readonly)
Key Moments - 2 Insights
Why does the variable not change after trying to assign a new value?
Because the variable was made readonly at step 2, any assignment after that (step 3) causes an error and does not change the value, as shown in the execution_table.
Does the script stop when the error occurs at step 3?
No, the script continues after the error, so the echo command at step 4 runs and prints the original value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'myvar' after step 3?
A'world'
B'hello'
Cundefined
Dempty string
💡 Hint
Check the 'Variable State' column at step 3 in the execution_table.
At which step does the script produce an error about modifying a readonly variable?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Output' and 'Notes' columns in the execution_table for the error message.
If we remove the 'readonly' command at step 2, what will be the output at step 4?
Aworld
Bbash error
Chello
Dempty
💡 Hint
Without readonly, the assignment at step 3 succeeds, changing the variable value.
Concept Snapshot
Declare a variable: myvar="value"
Make it readonly: readonly myvar
Trying to change it later causes an error
Readonly variables keep their value safe
Useful to prevent accidental changes
Full Transcript
This example shows how to create a readonly variable in bash. First, we assign 'hello' to myvar. Then we mark myvar as readonly using the readonly command. When we try to assign 'world' to myvar, bash gives an error and the value stays 'hello'. Finally, echo prints the unchanged value. This protects variables from accidental changes.