巴什可变间接Refrence [英] Bash Indirect Variable Refrence

查看:115
本文介绍了巴什可变间接Refrence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EDIT2:@glenn杰克曼我认为这将修复它,但它仍然在我的完整剧本犯错。为什么不工作?它是由于间接引用?

 #!/家用/ $ CURRENT_USER /桌面/预期
...
    COUNTER = 0
         而[$ COUNTER -lt $ NUM]。做
             让指数=​​ COUNTER + 1
             TMP = $用户_指数
             回声$密码变更{!TMP}
             回声$ {!TMP}
             sudo的passwd文件$ {!TMP}
             预计-exact[须藤]为$ CURRENT_USER密码
             发送$通\\ R
             相互作用
             预计-exact新密码
             发送$密码\\ r
             相互作用
             让COUNTER = COUNTER + 1
         DONE

编辑:!或/ $$适用于调用其他变量里面只是变量。我需要帮助那里的变量是一个字符串的一部分的情况。

我有关于Bash的间接变量引用一个简单的问题。

 的eval\\ $ {$用户_指数\\}#First尝试
回声\\ $$ {EVAL{用户_ \\ $指数}#Second尝试

基本上我有一个名为几个变量用户_ NUM 的,其中的 NUM 的是一个整数。这些变量包含一个字符串值。我想通过调用变量调用字符串值。然而,由于变量它里面的变量( NUM 的),我似乎无法得到它的工作。我已经通过手册页中的Bash间接引用看了看,但他们没有提到的地方的另一个变量内部变量连接到一个字符串的情况。

TLDR:我的问题是你如何做到这一点:

  $(var_ $ NUM)


解决方案

这是真的挺尴尬在bash:您需要一个临时变量来保存构造变量名:

  $ VAR_1 =打招呼
$ NUM = 1
$ TMP = var_ $ NUM
$回声$ {!TMP}
你好

数组是简单得多

  $ VAR =([1] =世界)
$回声$ {VAR [$ NUM]}
世界

EDIT2: @glenn jackman I thought this would fix it, but it still errs in my full script. Why isn't it working? Is it due to the indirect reference?

#!/home/$current_user/Desktop/expect
...
    COUNTER=0
         while [  $COUNTER -lt $num ]; do
             let index=COUNTER+1
             tmp=user_$index
             echo "Changing Password for " ${!tmp}
             echo ${!tmp}
             sudo passwd ${!tmp}
             expect -exact "[sudo] password for $current_user: "
             send "$pass\r"
             interact
             expect -exact "New password: "
             send "$password\r"
             interact
             let COUNTER=COUNTER+1 
         done

EDIT: The ! or the /$$ works for calling just variables inside of other variables. I need help for a case where the variable is part of a string.

I had a quick question regarding indirect variable references in Bash.

eval "\${user_$index\}"  #First attempt
echo \$${eval "{user_\$index}"} #Second attempt

Basically I have several variables named "user_num" where the num is a integer. Each of these variables contains a String value. I want to call that string value by calling the variable. However, since the variable has a variable inside of it (num), I can't seem to get it working. I've looked through the Man pages for Indirect References in Bash, but they don't mention cases where the variable inside of another variable is attached to a string.

TLDR: My question is how do you do this:

$(var_$num)

解决方案

This is really quite awkward in bash: you require a temporary variable to hold the constructed variable name:

$ var_1=hello
$ num=1
$ tmp=var_$num
$ echo ${!tmp}
hello

Arrays are much simpler

$ var=( [1]=world )
$ echo ${var[$num]}
world

这篇关于巴什可变间接Refrence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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