How to make variables as read only in bash shell linux ?

Variables in Linux can be made read only using the keyword “readonly”.

For example, if we want a variable to contain a value say 10 and must not be changed then we can achieve this using readonly.


Making a variable read only

### 1. Creating variable and assigning value
ngelinux:~ saket$ a=NGELinux
ngelinux:~ saket$ echo $a

### 2. Making a variable read only
ngelinux:~ saket$ a=NGEL
ngelinux:~ saket$ echo $a
ngelinux:~ saket$ readonly a

### 3. Read-only variable can't be modified.
ngelinux:~ saket$ a=NGELinux_again
-bash: a: readonly variable
ngelinux:~ saket$ 

### 4. We can't unset a read only variable.
ngelinux:~ saket$ unset a
-bash: unset: a: cannot unset: readonly variable

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

Leave a Reply

Notify of