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=x
x=$val

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

Leave a Comment