How to Create a Read-Only Variable in Shell Script

In Shell scripting, you can create variables that cannot be modified or unset once declared. This is achieved using the readonly command. Such variables are particularly useful for defining constants or critical values that should remain unchanged throughout the execution of a script.


Syntax

To declare a variable as read-only, use the following syntax:

readonly VARIABLE_NAME

Examples

1. Basic Read-Only Variable

#!/bin/bash
# Declare a variable
name="Gaurav"

# Make it read-only
readonly name

# Print the variable
echo "Name: ${name}"

# Attempt to modify the variable
name="Sharma"  # This will cause an error

# Attempt to unset the variable
unset name  # This will also cause an error

Output:

Name: Gaurav
./script.sh: line 8: name: readonly variable
./script.sh: line 11: unset: name: cannot unset: readonly variable

2. Read-Only Constants

Read-only variables are particularly useful for constants:

#!/bin/bash
# Define constants
readonly PI=3.14159
readonly SERVER_URL="https://api.example.com"

# Attempt to modify constants (will result in errors)
PI=3.14  # Error
SERVER_URL="https://new.example.com"  # Error

3. Using unset with Read-Only Variables

Read-only variables cannot be unset:

#!/bin/bash
# Declare a variable and make it read-only
name="ShellScripting"
readonly name

# Attempt to unset the variable
unset name  # This will cause an error

Output:

./script.sh: line 8: unset: name: cannot unset: readonly variable

How to Unset Non-Read-Only Variables

To remove a variable that is not read-only, you can use the unset command:

#!/bin/bash
# Declare a variable
name="TemporaryValue"

# Print the variable
echo "Before unset: ${name}"

# Unset the variable
unset name

# Attempt to print the variable
echo "After unset: ${name}"  # Will print nothing

Output:

Before unset: TemporaryValue
After unset:

Best Practices

  1. Use for Constants:

    • Always use readonly for variables that represent constants or configurations that should not be altered during script execution.
  2. Avoid Overuse:

    • Do not use readonly for variables that need to be updated dynamically.
  3. Error Handling:

    • Be cautious when modifying scripts with read-only variables, as they can cause unexpected errors if attempts are made to modify them.

Demo Video

Click Here for Demo Video