Mark a shell variable or function as read-only
readonly [-aAf] [name[=value] ...]
readonly -p
-a: points to the array.
-A: Points to an associative array.
-f: Point to function.
-p: Display all read-only variables.
--: The options after it are invalid.
name (optional): variable name or function name
value (optional): the value of the variable
readonly returns true unless you provide an illegal option or illegal name.
# Define variables and add read-only attributes
readonly var1=13 var2
readonly -a arr1=(1 2 3 4 5) arr2=('z' 'x' 'c')
# Must have '-A' option
readonly -A dict1=(['key1']='value1')
# Define variables and functions first, and then add read-only attributes to them
max=3
readonly max
#You don’t need to add `declare -a` when defining the array
seasons=('spring' 'summer' 'autumn' 'winter')
# You can add the `-a` option when adding a read-only attribute to an array
readonly seasons
declare -A man=(['age']=23 ['height']='190cm')
# You can add the `-A` option when adding read-only properties to associative arrays
readonly man
function foo(){ echo 'bar'; }
# You must add the `-f` option when adding a read-only attribute to a function
readonly -f foo
# Display all read-only variables. The following two commands have the same display results.
readonly
readonly -p
# Display all arrays with read-only attributes
readonly -a
# Display all associative arrays with read-only properties
readonly -A
# Display all functions with read-only attributes
readonly -f
For read-only variables, if the user modifies its value, an error will be reported immediately. For example, use this command to define a read-only variable "test" and initialize its value to "ok". Enter the following command:
[root@localhost ~]# readonly test='ok' #Define read-only variables and initialize them
Then when the user directly modifies the read-only variable, an error will be reported, as shown below:
[root@localhost ~]# test='my' #Trying to modify the value of a read-only variable
-bash: test: readonly variable
When the user attempts to modify the value of a read-only variable, he or she will be prompted that the variable is read-only.