如何将变量名传递给函数并使其在 bash 之外可用?

How to pass variable name to a function and get it available outside in bash?

如何将变量名传递给函数并在其作用域外使用它?

我试过了,但没用:

questionPrompt() {
    while [ -z "$answer" ]; do
    echo 
    read answer
    =$answer
    done
}

questionPrompt "Which color do you like?" "COLOR"

echo $COLOR

它说:COLOR=red: command not found

使用declare:

declare -g "=$answer"

declare -gn var=
var="$answer"

然而,macOS (3.2) 附带的 bash 版本不支持 declare -g;您可以改用 printf

printf -v "" '%s' "$answer"