一个函数中使用bash间接变量赋值 [英] Bash indirect variable assignment inside a function

查看:104
本文介绍了一个函数中使用bash间接变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,用户输入需要进行评估几次,该解决方案IM工作是将评估位转换成一个函数,只需调用函数每次我需要评估的输入时间。
现在的问题是,虽然,当我尝试更新 $ 1 变量(即referes给函数的第一个变量参数)我得到错误信息$变量命令未找到 。

I have a script where the user input needs to be evaluated several times, the solution im working on is to put the evaluation bits into a function, and simply call the function every time i need to evaluate the input. The problem is though that when im trying to update the $1 variable (that referes to the first variable parameter of the function) I get the error message "$VARIABLE command not found".

下面是code:

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

给出了这样的输出:

Gives this output:

5
./test: line 38: 5=sun: command not found

好吧,继续前进......

Ok, moving on...

现在这几乎是正确的,但什么IM后的doctype =日晒,5 =太阳,换句话说,我需要的 $ 1 变量名称而不是它的价值。更改行的eval $ 1 =$ {数组[selid]}评估DOCTYPE =$ {数组[selid]}修正了这个特定的实例。但是,当我需要运行在具有不同名称的不同变量这一功能,这并不解决我的问题。

Now this is almost correct, but what im after is doctype=sun, not 5=sun, in other words I need the $1 variable name not its value. Changing the line eval $1="${array[selid]}" to eval doctype="${array[selid]}" fixes this particular instance. But this does not fix my problem as I need to run this function on different variables with different names.

推荐答案

也许不完全了解你想要达到什么样的,但检查下一个例子:

Maybe not fully understand what you want achieve, but check the next example:

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做任何事情的在调用的函数,你应该通过该变量的名称,而不是他的价值。所以调用函数

In short - when you want to do anything with the variable NAME in an called function, you should pass the NAME of the variable and NOT his value. So call the function

somefunc NAME

而不是

somefunc $NAME

和使用上述结构得到函数内部的名称和值。

and use the above constructs to get the name and value inside the function.

这篇关于一个函数中使用bash间接变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆