How to delete readonly variable in bash?

6

3

$ mySite="superuser"
$ readonly mySite
$ unset mySite
bash: unset: mySite: cannot unset: readonly variable

How can we delete mySite, as it is a readonly variable?

Yishu Fang

Posted 2012-10-27T03:52:54.697

Reputation: 261

As said below, there is a thread on StackOverflow with answers, with and without GDB.

– bufh – 2019-12-12T14:12:30.497

Answers

4

You can't delete mySite. The whole point of the readonly command is to make it final and permanent (until the shell process terminates). If you need to change a variable, don't mark it readonly.

Isaac Rabinovitch

Posted 2012-10-27T03:52:54.697

Reputation: 2 645

1

See https://stackoverflow.com/a/21294582/642372

This is dark magic. It uses gdb to tell the bash process to clear the variable by calling an internal C function.

mySite="superuser"
readonly mySite
gdb -n <<EOF >>/dev/null 2>&1
attach $$
call unbind_variable("mySite")
detach
quit
EOF

You should never have this in production. I have it in my .bashrc.

Walker Hale IV

Posted 2012-10-27T03:52:54.697

Reputation: 119

1

Walker Hale IV's solution can be expressed in a much shorter fashion using options available in more recent versions of gdb:

gdb --batch-silent --pid=$$ --eval-command='call unbind_variable("mySite")'

Again, this is dark magic that should be kept well away from production environments.

michaelb958--GoFundMonica

Posted 2012-10-27T03:52:54.697

Reputation: 261