Modifying a read-only variable

April 2018

Solution 1

A variable declared as read-only can not be modified during outgoing process.
But if the variable is exported in a child shell it may be modified.


if [ "$PROC_PID" != "$PPID" ]; then
  export PROC_PID=$$
  echo "initial $var"

  declare -r var

  export var
  $0 & # child process 
  echo "before $var"
  echo "after $var"

Solution 2

Making use of indirect development.

# Declaration of read-only Variable
$ readonly Z="Y"
$ echo $Z

# Suppression test 
$ unset Z
-l: unset: Z: cannot unset: readonly variable

# Replacement test
$ Z=W
-l: Z: readonly variable

# Declaration of an indirect variable
$ Y=W
$ echo "$Y"

# Development of variable with indirection
$ echo "${!Z}"

Published by netty5. Latest update on August 13, 2009 at 07:05 AM by jak58.
This document, titled "Modifying a read-only variable," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (
Changing password via a script
Shell - Creating an empty file