How to unset variables in linux bash shell (normal and read only variables) ?

We all know that a variable is defined by simply assigning a value to it.

However bash shell also provides a feature to unset it, in order to free it up from the system memory.

Let us have a look how to do this.

1. Setting or defining a new variable.

ngelinux:~ saket$ b=10
ngelinux:~ saket$ echo $b


2. Unsetting variable.

ngelinux:~ saket$ unset b
ngelinux:~ saket$ echo $b

ngelinux:~ saket$ 


3. Making a variable read only.

### Define a variable
ngelinux:~ saket$ a=NGEL
ngelinux:~ saket$ echo $a

### Make this variable read-only
ngelinux:~ saket$ readonly a

### Try to assign a new value to it.
### It throws an error as the variable is read only.
ngelinux:~ saket$ a=NGELinux_again
-bash: a: readonly variable
ngelinux:~ saket$ 


4.  Unsetting a readonly variable
Practically a read only variable can’t be unset and exists the whole lifetime of its parent process.

ngelinux:~ saket$ echo $a

ngelinux:~ saket$ unset a
-bash: unset: a: cannot unset: readonly variable


How to unset a read only variable in debugging mode ?

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



We can also run above command in batch mode like below.
# gdb -ex ‘call unbind_variable(“a”)’ –pid=$$ –batch

0 0 votes
Article Rating
Notify of

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments
4 years ago

[…] Still if you want to unset a read-only variable, then check out this article here. […]