readonly – Mark a shell variable or function as read-only

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

Overview

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:

readonly my_var

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

Examples

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:

readonly important_var

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.

Options

The readonly command has the following options:

Option Description
-f Marks a function as read-only.
-n Marks a variable as non-exported.
-p Displays a list of all read-only variables and functions.

Troubleshooting Tips

  • 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 readonly command.
  • If you need to change the value of a read-only variable or function, you will need to unset it first using the unset command.

Notes

  • The readonly command 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.
  • The readonly command can be used in conjunction with the declare command to set additional attributes for variables or functions, such as their data type or scope.