在函数内部使用Bash间接变量赋值

Dan*_*and 5 variables bash function

我有一个脚本,用户输入需要进行评估数次,该解决方案IM工作就是把评估位转换成函数,只需调用函数每次我需要评估的输入时间.问题是,当我试图更新$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
}
Run Code Online (Sandbox Code Playgroud)

这个命令:

input_handler $doctype $docpath
Run Code Online (Sandbox Code Playgroud)

给出这个输出:

5
./test: line 38: 5=sun: command not found
Run Code Online (Sandbox Code Playgroud)

好的,继续......

现在这几乎是正确的,但是后面的内容是doctype = sun,而不是5 = sun,换句话说,我需要$1变量名而不是它的值.更改行eval $1="${array[selid]}"eval doctype="${array[selid]}"修复此特定实例.但这并不能解决我的问题,因为我需要在不同名称的不同变量上运行此函数.

use*_*621 -1

位置参数是只读的。所以你想做的事情是不可能的。你应该做类似的事情

foo=$1
Run Code Online (Sandbox Code Playgroud)

然后使用$foo而不是$1