Bash间接变量参考 [英] Bash indirect variable reference

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

问题描述

@glenn jackman我以为这可以解决它,但是在我的完整脚本中仍然出错.为什么不起作用?是由于间接引用吗?

@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

!或/$$只能在其他变量中调用变量.如果变量是字符串的一部分,我需要帮助.

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.

关于Bash中的间接变量引用,我有一个简短的问题.

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

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

基本上,我有几个名为"user_ num "的变量,其中 num 是整数.这些变量中的每一个都包含一个String值.我想通过调用变量来调用该字符串值.但是,由于变量内部有一个变量( num ),所以我似乎无法使其正常工作.我浏览了Bash中间接引用的手册页,但没有提到将另一个变量内的变量附加到字符串的情况.

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:我的问题是你如何做到这一点:

TLDR: My question is how do you do this:

$(var_$num)

推荐答案

在bash中,这确实很尴尬:您需要一个临时变量来保存构造的变量名称:

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

数组要简单得多

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

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

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