Unset readonly variable in bash

Kokizzu picture Kokizzu · Jul 1, 2013 · Viewed 59.1k times · Source

How do I unset a readonly variable in Bash?

$ readonly PI=3.14

$ unset PI
bash: PI: readonly variable

or is it not possible?

Answer

anishsane picture anishsane · Jul 1, 2013

Actually, you can unset a readonly variable. but I must warn that this is a hacky method. Adding this answer, only as information, not as a recommendation. Use it at your own risk. Tested on ubuntu 13.04, bash 4.2.45.

This method involves knowing a bit of bash source code & it's inherited from this answer.

$ readonly PI=3.14
$ unset PI
-bash: unset: PI: cannot unset: readonly variable
$ cat << EOF| sudo gdb
attach $$
call unbind_variable("PI")
detach
EOF
$ echo $PI

$

A oneliner answer is to use the batch mode and other commandline flags, as provided in F. Hauri's answer:

$ sudo gdb -ex 'call unbind_variable("PI")' --pid=$$ --batch

sudo may or may not be needed based on your kernel's ptrace_scope settings. Check the comments on vip9937's answer for more details.