0
0
Bash Scriptingscripting~5 mins

Read-only variables (readonly) in Bash Scripting

Choose your learning style9 modes available
Introduction
Read-only variables help keep important values safe from accidental changes in your script.
When you want to store a value that should never change during the script.
To protect configuration settings from being modified by mistake.
When sharing variables between functions but want to keep them constant.
To avoid bugs caused by accidentally changing critical data.
When you want to make your script easier to understand by marking fixed values.
Syntax
Bash Scripting
readonly VARIABLE_NAME=VALUE
# or
readonly VARIABLE_NAME
Use 'readonly' before a variable name to make it unchangeable.
You can set the value when declaring or make an existing variable readonly.
Examples
Sets PI as a read-only variable with value 3.14.
Bash Scripting
readonly PI=3.14
# Now PI cannot be changed
Makes the existing variable NAME read-only.
Bash Scripting
NAME="Alice"
readonly NAME
# NAME is now read-only
Trying to change a read-only variable causes an error.
Bash Scripting
readonly MAX_USERS=100
MAX_USERS=200
# This will cause an error
Sample Program
This script sets GREETING as read-only, prints it, then tries to change it and prints again. The change will fail.
Bash Scripting
#!/bin/bash
readonly GREETING="Hello"
echo $GREETING
# Trying to change GREETING
GREETING="Hi"
echo $GREETING
OutputSuccess
Important Notes
Trying to change a read-only variable will cause an error and the variable keeps its original value.
Read-only variables help prevent accidental mistakes in your scripts.
You cannot unset a read-only variable with 'unset'.
Summary
Use 'readonly' to make variables unchangeable.
Read-only variables protect important values in your script.
Trying to modify a read-only variable causes an error.