Declaring global variable inside a function
declare
inside a function doesn't work as expected.I needed read-only global variables declared in a function.I tried this inside a function but it didn't work:
declare -r MY_VAR=1
But this didn't work. Using the readonly
command did:
func() { readonly MY_VAR=1}funcecho $MY_VARMY_VAR=2
This will print 1 and give the error "MY_VAR: readonly variable" for the second assignment.