我有一个脚本,其中用户输入需要被评估几次,我正在处理的解决方案是将评估位放入一个函数中,并且每次我需要评估输入时只需调用该函数。
问题是,当我尝试更新 $1
变量(指函数的第一个变量参数)时,我收到错误消息“找不到 $VARIABLE 命令”。
代码如下:
function input_handler() {
if is_integer $1; then
selid="$1 -1"
if [[ "$1" -le "0" ]]; then
echo "Please use a simple positive number!"
else
if [[ "$1" -le "${#array[*]}" ]]; then
eval $1="${array[selid]}"
echo "Ok, moving on..."
else
echo "That number seems too large, try again?"
fi
fi
else
if [ -e $2/$1 ]; then
echo "Ok, moving on..."
else
echo "That item is not on the list, try again!"
fi
fi
}
还有这个命令:
input_handler $doctype $docpath
给出这个输出:
5
./test: line 38: 5=sun: command not found
好的,继续...
现在这几乎是正确的,但我要的是 doctype=sun,而不是 5=sun,换句话说,我需要 $1
变量名而不是它的值。将 eval $1="${array[selid]}"
行更改为 eval doctype="${array[selid]}"
可修复此特定实例。但这并不能解决我的问题,因为我需要对具有不同名称的不同变量运行此函数。
最佳答案
也许不完全理解你想要达到的目的,但是检查下一个例子:
weirdfunc () {
echo " weirdfunc: variable name is: $1"
echo " weirdfunc: variable value is: ${!1}"
eval "$1=$(( ${!1} + 1))" #assign
}
myvar="5"
echo "the value of myvar before: $myvar"
weirdfunc myvar #call with the NAME not with the value, so NOT weridfunc $myvar
echo "the value of myvar after: $myvar"
简而言之 - 当您想在被调用的函数中对变量 NAME 做任何事情时,您应该传递变量的名称而不是他的值。所以调用函数
somefunc NAME
代替
somefunc $NAME
并使用上述构造在函数内获取名称和值。
关于函数内的 Bash 间接变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131218/