我有一个脚本需要多次评估用户输入,我正在处理的解决方案是将评估位放入一个函数中,每次我需要评估输入时调用该函数.
问题是,当我试图更新$1变量(引用该函数的第一个变量参数)时,我收到错误消息“$VARIABLE command not found”.
问题是,当我试图更新$1变量(引用该函数的第一个变量参数)时,我收到错误消息“$VARIABLE command not found”.
这是代码:
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做任何事情时,你应该传递变量的NAME而不是他的值.所以调用函数
somefunc NAME
代替
somefunc $NAME