Deal with readonly variables in bash

As we know there’s a kind of read-only variables in bash in common linux system, typically $BASH_COMPLETION and $BASH_COMPLETION_DIR are both readonly variables. This post will focus on the following two topics, how can we set readonly variables in Bash, and how can we unset them.

How can we set a variable to be read-only?

Basically, it’s quite easy, you can just run readonly command like this:

planet@admon:~$ cax=janghiz
planet@admon:~$ readonly cax
planet@admon:~$ echo $cax
planet@admon:~$ cax=website
-bash: cax: readonly variable

From the above lines, we know that the readonly variables cannot be changed again when they set to be readonly.
Fine, but let’s say if I now want to make it updatable again, how can I deal with it? Is this possible with eg, “readwrite cax” or something similiar? Alright, let go further to the second question:

How can I unset an readonly variable?

Actually, it’s NOT that easy!
The man pages for bash says, once a variable is marked as readonly, it cannot be unset.

planet@admon:~$ unset cax
-bash: unset: cax: cannot unset: readonly variable

Typeset says:

    typeset -r     Make names readonly.  These names cannot then be
assigned values by subsequent assignment statements or unset.

Also unset says:

    unset [-fv] [name ...]
          For each name, remove the corresponding variable or function.  If
          no  options  are  supplied,  or the -v option is given, each name
          refers to a shell  variable.  Read-only variables may not be unset.

Your best option would be to kill the shell, or run the readonly mode within a subshell. Something like:

planet@admon:~$ {(cax=janghiz; readonly cax; echo "var1-cax=$cax"); cax=da; echo "var2-cax=$cax"; unset b; echo; "$b";}

So the only way to unset a readonly variable is either to use it in a subshell, or kill your currently shell.

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *