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
10

 

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
NGEL

### 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
NGEL

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")
detach
EOF
$ echo $a

$

 

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

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
trackback

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