how to unset readonly variable in Bash?
$ readonly PI=3.14
$ unset PI
bash: PI: readonly variable
or is it not possible?
how to unset readonly variable in Bash?
$ readonly PI=3.14
$ unset PI
bash: PI: readonly variable
or is it not possible?
Shortly: inspired by anishsane's answer
But with simplier syntax:
My
destroy
function:Or How to check variable meta data...
You could copy this to a bash source file called
destroy.bash
, for sample...Explanation:
unset
instead ofgdb
if readonly flag not presentwhile read ... result= ... done
get result ofcall
ingdb
outputgdb
syntax with use of--pid
and--ex
(seegdb --help
).In use:
Using GDB is terribly slow. Try ctypes.sh instead. It works by using libffi to directly call bash's unbind_variable() instead, which is every bit as fast as using any other bash builtin:
First you will need to install ctypes.sh:
See https://github.com/taviso/ctypes.sh for a full description and docs.
For the curious, yes this lets you call any function within bash, or any function in any library linked to bash, or even any external dynamically-loaded library if you like. Bash is now every bit as dangerous as perl... ;-)
According to the man page:
If you have not yet exported the variable, you can use
exec "$0" "$@"
to restart your shell, of course you will lose all other un-exported variables as well. It seems if you start a new shell withoutexec
, it loses its read-only property for that shell.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 recommendation. Use 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.
No, not in the current shell. If you wish to assign a new value to it, you will have to fork a new shell where it will have a new meaning and will not be considered as
read only
.One other way to "unset" a read-only variable in Bash is to declare that variable read-only in a disposable context:
While this is not "unsetting" within scope, which is probably the intent of the original author, this is definitely setting a variable read-only from the point of view of baz() and then later making it read-write from the point of view of baz(), you just need to write your script with some forethought.