readonly command in Linux is used to mark shell variables or functions as read-only. This means that the value of the variable or function cannot be changed by subsequent commands or scripts. The purpose of this command is to prevent accidental changes to important variables or functions that could cause errors or security issues.
To mark a shell variable or function as read-only, use the
readonly command followed by the name of the variable or function. For example, to mark a variable named
my_var as read-only, use the following command:
Similarly, to mark a function named
my_func as read-only, use the following command:
readonly -f my_func
Once a variable or function has been marked as read-only, any attempt to change its value will result in an error message. For example, if we try to change the value of
my_var, we will see the following error message:
my_var: readonly variable
Likewise, if we try to redefine a read-only function, we will see the following error message:
my_func: readonly function
Here are some examples of how to use the
readonly command in different scenarios:
Example 1: Protecting important variables
Suppose we have a script that relies on a variable named
important_var. We want to make sure that this variable cannot be accidentally changed by other commands or scripts. To do this, we can mark
important_var as read-only using the following command:
Now, if any subsequent commands or scripts try to change the value of
important_var, they will receive an error message.
Example 2: Protecting critical functions
Suppose we have a script that defines a critical function named
do_not_run. We want to make sure that this function cannot be accidentally redefined or modified by other commands or scripts. To do this, we can mark
do_not_run as read-only using the following command:
readonly -f do_not_run
Now, if any subsequent commands or scripts try to redefine or modify
do_not_run, they will receive an error message.
readonly command has the following options:
||Marks a function as read-only.|
||Marks a variable as non-exported.|
||Displays a list of all read-only variables and functions.|
- If you receive an error message that a variable or function is read-only, check to make sure that you have not accidentally marked it as such using the
- If you need to change the value of a read-only variable or function, you will need to unset it first using the
readonlycommand only works within the current shell session. If you open a new shell session, any read-only variables or functions will no longer be marked as such.
readonlycommand can be used in conjunction with the
declarecommand to set additional attributes for variables or functions, such as their data type or scope.