bash根据variables名称分配variables

我想写一个bash函数,我提供一个string,它将值“hi”赋给一个带有该string名称的variables。 我确信这个答案以前,但我不知道在手册中查找的关键字。

myfunc() { ## some magic with $1 ## please help me fill in here. } myfunc "myvar" echo $myvar > hi 

回答之后。 多谢你们。 我写了一个函数来查找一个环境variables,并提示它,如果它不存在。 将不胜感激任何改进。 我相信这是有效的。

 get_if_empty() { varname=$1 eval test -z $`echo ${varname}`; retcode=$? if [ "0" = "$retcode" ] then eval echo -n "${varname} value: " read `echo $1` # get the variable name fi eval echo "$1 = $`echo ${varname}`" } 

这是用法:

 get_if_empty MYVAR 

man bash

  eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0 

所以

 myfunc() { varname=$1 eval ${varname}="hi" } myfunc "myvar" echo $myvar 

你的get_if_empty函数比它需要的复杂得多。 这是一个非常简化的版本:

 get_if_empty() { if [ -z "${!1}" ]; then # ${!var} is an "indirect" variable reference. read -p "$1 value: " $1 fi } 
 #!/bin/bash indirect() { [[ "$1" == "get" ]] && { local temp="$2" echo ${!temp} } [[ "$1" == "set" ]] && read -r $2 <<< "$3" } indirect set myvar Hi echo $myvar Hi=$(indirect get myvar) indirect get Hi double=$(indirect get $Hi) indirect get $double