17 April 2021
It is possible to make immutable variables or functions in bash script using readonly
command, in this way it could be possible avoid to overwrite variables in complex environment.
If you try to overwrite a readonly variable then an error message will be appear bash: ${VARIABLE NAME}: readonly variable
.
Example:
$ readonly MY_VAR=test
$ readonly -p
$ docker run -it ubuntu /bin/bash
root@9a44663a36f0:/# readonly -p
declare -r BASHOPTS="checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote:force_fignore:globasciiranges:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath"
declare -ar BASH_VERSINFO=([0]="5" [1]="0" [2]="17" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
declare -ir EUID="0"
declare -ir PPID="0"
declare -r SHELLOPTS="braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor"
declare -ir UID="0"
root@9a44663a36f0:/# readonly MY_VAR=test
root@9a44663a36f0:/# MY_VAR=test2
bash: MY_VAR: readonly variable
root@9a44663a36f0:/# echo ${MY_VAR}
test
root@9a44663a36f0:/# readonly -p
declare -r BASHOPTS="checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote:force_fignore:globasciiranges:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath"
declare -ar BASH_VERSINFO=([0]="5" [1]="0" [2]="17" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
declare -ir EUID="0"
declare -r MY_VAR="test"
declare -ir PPID="0"
declare -r SHELLOPTS="braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor"
declare -ir UID="0"
readonly --help