TrumanWong

readonly

Mark a shell variable or function as read-only

grammar

readonly [-aAf] [name[=value] ...]
readonly -p

The main purpose

  • Define one or more variables and set read-only attributes.
  • Set read-only attributes for one or more defined variables.
  • Display all variables that contain read-only attributes.
  • Set read-only attributes for one or more defined functions.
  • Show all functions that contain read-only attributes.

Options

-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.

Parameters

name (optional): variable name or function name
value (optional): the value of the variable

return value

readonly returns true unless you provide an illegal option or illegal name.

example

# 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

Common mistakes

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.

Notice

  1. This command is a built-in bash command. For related help information, please see the help command.
  2. declare +r cannot remove read-only attributes, and unset cannot delete read-only variables.