我想编写一个 bash 函数,在其中提供一个字符串,然后它将值“hi”分配给具有该字符串名称的变量。我确信之前已经回答过这个问题,但我不知道在手册中查找关键字。
myfunc() {
## some magic with $1
## please help me fill in here.
}
myfunc "myvar"
echo $myvar
> hi
回答后。谢谢大家。我写了一个函数来查找环境变量,如果不存在则提示输入。如果有任何改进,我将不胜感激。我相信它有效。
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
答案1
从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
答案2
您的 get_if_empty 函数比它需要的要复杂得多。这是一个简化得多的版本:
get_if_empty() {
if [ -z "${!1}" ]; then # ${!var} is an "indirect" variable reference.
read -p "$1 value: " $1
fi
}
答案3
#!/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