How do I create both local
and declare -r
(read-only) variable in bash?
If I do:
function x {
declare -r var=val
}
Then I simply get a global var
that is read-only
If I do:
function x {
local var=val
}
If I do:
function x {
local var=val
declare -r var
}
Then I get a global again (I can access var
from other functions).
How to combine both local and read-only in bash?
To add more nuance, readonly may be used to change a locally declared variable property to readonly, not affecting scope. Note: adding -g flag to the declare statement (e.g. declare -rg a="a1" ) makes the variable scope global. (thanks @chepner). Note: readonly is a "Special Builtin".
Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed. /bin/sh: NAME: This variable is read only.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
This answer is useful. This answer is not useful. Show activity on this post. ${1#*-} deletes the shortest match of *- , a glob-like pattern from $1 variable. E.g. abcdef-xyz-foo -> xyz-foo.
Even though help local
doesn't mention it in Bash 3.x, local
can accept the same options as declare
(as of at least Bash 4.3.30, this documentation oversight has been corrected).
Thus, you can simply do:
local -r var=val
That said, declare
inside a function by default behaves the same as local
, as @ruakh states in a comment, so your 1st attempt should also have succeeded in creating a local read-only variable.
In Bash 4.2 and higher, you can override this with declare
's -g
option to create a global variable even from inside a function (Bash 3.x does not support this.)
Thanks, Taylor Edmiston:
help declare
shows all options support by both declare
and local
.
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