In Bash, you can create a read-only variable
declare -r somevar='bla'
I tried to find something similar in POSIX sh
, but the only thing that comes close is this phrase in the set
documentation:
[...] read-only variables cannot be reset.
How can I create such a read-only variable?
Readonly can be declared only at the class level, not inside the method. Readonly can not be declared using static keywords because they are by default static. Readonly constant's value can be set through the reference variable. Readonly constant variables are a runtime time constant variable.
3.7 Read-Only Variables Read-only variables can be used to gather information about the current template, the user who is currently logged in, or other current settings. These variables are read-only and cannot be assigned a value.
Using the readonly command, you can assign a particular value to a variable that can neither be changed nor modified by subsequent assignments nor be unset.
You can make use of readonly
:
$ var="hello"
$ readonly var
$ echo $var
hello
$ var="bye"
sh: var: readonly variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With