Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a "read-only variable"?

Tags:

shell

posix

sh

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?

like image 824
rubenvb Avatar asked Sep 26 '14 07:09

rubenvb


People also ask

How do you create 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.

What is a read only 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.

Which command is used to make a variable read only?

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.


1 Answers

You can make use of readonly:

$ var="hello"
$ readonly var
$ echo $var
hello
$ var="bye"
sh: var: readonly variable
like image 91
fedorqui 'SO stop harming' Avatar answered Oct 04 '22 21:10

fedorqui 'SO stop harming'