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

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

1

3 Answers 3

8

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.

9

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.

2
  • Got error: 'unbind_variable' has unknown return type; cast the call to its declared return type. The declared return type is int (github.com). Success after adding (int): gdb --batch-silent --pid=$$ --eval-command='call (int) unbind_variable("mySite")' May 12, 2021 at 19:31
  • 1
    It's not just dark magic, it's very brittle magic, too. As it appears to rely on having a non-stripped version of Bash or at least matching symbols installed. This isn't a default on most systems on which I work. May 16, 2023 at 15:07
3

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

2
  • Doesn't seem to work in shell. How can I make this work with sh? Feb 1, 2022 at 9:37
  • @NickPodratz different shell, different functions. You'd have to consult specifically the source code of your shell and try to find the function that restricts unset-ting any readonly or -- as is done above -- one that would be called after the check and outright unbinds the variable. That's why this is a very brittle "solution" indeed. May 16, 2023 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .