Read-Only Variables in Linux

March 27, 2021

During shell scripting, we may need a few variables, which cannot be modified. This may be needed for security reasons. We can declare variables as read-only by using the following read-only command:

$ readonly currency=Dollars

Let’s try to remove the variable:

$ unset currencybash: unset: currency: cannot unset: readonly variable

If we try to change or remove the read-only variable in the script, it will give the following error:

#!/bin/bash 
AUTHOR="Ganesh Naik" 
readonly AUTHOR 
AUTHOR="John"

This will produce the following result:

Output:

/bin/sh: AUTHOR: This variable is read only.

Another technique is as follows:

declare  -r  variable=1 
echo "variable=$variable" 
(( var1++ ))

The output after execution of the script is this:

Output:

line 4: variable: readonly variable

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

three × one =