Declaring global variable inside a function Declaring global variable inside a function shell shell

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.


Since this is tagged shell, it is important to note that declare is a valid keyword only in a limited set of shells, so whether it supports -g is moot. To do this sort of thing in a generic Bourne shell, you can just use eval:

eval ${arg}=5


I think you need the printf builtin with its -v switch:

func() {    printf -v "$var" '5'}var=var_namefuncecho "$var_name"

will output 5.