Declaring global variable inside a function

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

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
}
func
echo $MY_VAR
MY_VAR=2

This will print 1 and give the error "MY_VAR: readonly variable" for the second assignment.


Using "eval" (or any direct assignment) can give you headaches with special characters (or issues with value injection etc).

I've had great success just using "read"

$ function assign_global() {
>   local arg="$1"
>   IFS="" read -d "" $arg <<<"$2"
>}
$ assign_global MYVAR 23
echo $MYVAR
23
$ assign_global MYVAR "\"'"
"'

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

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

will output 5.

Tags:

Shell

Bash

Scope