Indirect variable assignment in bash Indirect variable assignment in bash bash bash

Indirect variable assignment in bash


A slightly better way, avoiding the possible security implications of using eval, is

declare "$var=$val"

Note that declare is a synonym for typeset in bash. The typeset command is more widely supported (ksh and zsh also use it):

typeset "$var=$val"

In modern versions of bash, one should use a nameref.

declare -n var=xx=$val

It's safer than eval, but still not perfect.


Bash has an extension to printf that saves its result into a variable:

printf -v "${VARNAME}" '%s' "${VALUE}"

This prevents all possible escaping issues.

If you use an invalid identifier for $VARNAME, the command will fail and return status code 2:

$ printf -v ';;;' '%s' foobar; echo $?bash: printf: `;;;': not a valid identifier2


eval "$var=\$val"

The argument to eval should always be a single string enclosed in either single or double quotes. All code that deviates from this pattern has some unintended behavior in edge cases, such as file names with special characters.

When the argument to eval is expanded by the shell, the $var is replaced with the variable name, and the \$ is replaced with a simple dollar. The string that is evaluated therefore becomes:

varname=$value

This is exactly what you want.

Generally, all expressions of the form $varname should be enclosed in double quotes, to prevent accidental expansion of filename patterns like *.c.

There are only two places where the quotes may be omitted since they are defined to not expand pathnames and split fields: variable assignments and case. POSIX 2018 says:

Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.

This list of expansions is missing the parameter expansion and the field splitting. Sure, that's hard to see from reading this sentence alone, but that's the official definition.

Since this is a variable assignment, the quotes are not needed here. They don't hurt, though, so you could also write the original code as:

eval "$var=\"the value is \$val\""

Note that the second dollar is escaped using a backslash, to prevent it from being expanded in the first run. What happens is:

eval "$var=\"the value is \$val\""

The argument to the command eval is sent through parameter expansion and unescaping, resulting in:

varname="the value is $val"

This string is then evaluated as a variable assignment, which assigns the following value to the variable varname:

the value is value