How to Make a Variable read-only (constant) in Bash and Korn Shell

Creating Bourne Shell Constants

A variable can be made read-only with the following syntax:

readonly var[=value]

The square brackets around =value mean that the assignment of a value is not always necessary. For instance, if the variable had previously been created and assigned a value, and you now want to make it read-only (and not change its current value), do not use =value.

If the variable did not previously exist, and you make it read-only, you may never assign a value to the variable. The value of a read-only variable cannot be changed. This is why read-only variables are referred to as constants:

$ sh
$ var=constant
$ readonly var
$ unset var 
var: is read only
$ var=new_value 
var: is read only

Creating Korn Shell Constants

A variable can be made read-only by using either of the following syntaxes:

typeset -r var[=value] 
readonly var[=value]

The following is a Korn shell example:

$ ksh
$ typeset -r cvar=constant
$ unset cvar 
ksh: cvar: is read only
$ cvar=new_value 
ksh: cvar: is read only
Related Post