What if a tiny mistake changed your script's key settings without you noticing?
Why Read-only variables (readonly) in Bash Scripting? - Purpose & Use Cases
Imagine you write a script to set important values like a password or a configuration path. You share it with others, but someone accidentally changes those values later in the script or while running it.
Without protection, variables can be changed by mistake or on purpose, causing your script to behave wrongly or fail. Tracking down where the value changed can be frustrating and time-consuming.
Using read-only variables locks their values so they cannot be changed after setting. This keeps your important data safe and your script reliable.
config_path="/usr/local/app" # later someone does config_path="/tmp/hacked"
readonly config_path="/usr/local/app" # trying to change now causes error config_path="/tmp/hacked" # error
It enables you to protect critical values in your scripts, preventing accidental or harmful changes.
In deployment scripts, setting a read-only variable for the server address ensures no part of the script can accidentally redirect commands to the wrong server.
Read-only variables prevent accidental changes.
They make scripts more reliable and easier to debug.
Protect important data by marking variables as readonly.