简体   繁体   English

BASH将数组元素更改为变量

[英]BASH Changing Array element into Variable

I'm trying to create variables from array elements and check value of my created variable in sourcefile. 我正在尝试从数组元素创建变量,并在源文件中检查我创建的变量的值。

MySourceFile: MySourceFile:

value1abc="10"
value2efg="30"
value3ade="50"
value4tew="something else"
onemorevalue="192.168.1.0"

Script Code : 脚本代码:

declare -a CfgData
CfgData=("value1abc" "value2efg" "value3ade" "value4tew" "othervalue" "onemorevalue")
COUNTER="0"

source MySourceFile

until [ $COUNTER == ${#CfgData[@]}  ]; do
    value=$[${CfgData[$COUNTER]}]
    echo -ne "\\n${CfgData[$COUNTER]}=\"$value\""\\n\\n
    let COUNTER+=1
done

Script works fine until it comes to values which contain data other than pure numbers (letters, spaces, dots, generally all characters) in which case : 脚本工作正常,直到包含除纯数字(字母,空格,点,通常所有字符)之外的数据的值,在这种情况下:

value="randomcharacters" # Gives me "0"
value="something else" & value="192.168.1.0" # line XX: 192.168.1.0: syntax error: invalid arithmetic operator (error token is ".168.1.0")

I'm pretty sure I'm missing something elementary but I cannot figure it out now :P. 我很确定我错过了一些基本的东西,但我现在无法理解:P。

First, the $[...] bash syntax is obsolete and should not be used. 首先, $[...] bash语法已过时,不应使用。

Now, it evaluates its content as an arithmetic expression. 现在,它将其内容评估为算术表达式。 When you put in a string, is is interpreted as a variable, and its value again evaluated as an arithmetic expression. 当您输入字符串时,is被解释为变量,并且其值再次被计算为算术表达式。 When a variable is unset, it evaluates to zero. 取消设置变量时,它的计算结果为零。

If you put a string with a single word, these rules make it expand to zero. 如果您输入一个包含单个单词的字符串,则这些规则会将其扩展为零。 If you put in a string with multiple words, the expansion fails, because the words are interpreted as variables, with no intermediate arithmetic operator, which is an error. 如果放入一个包含多个单词的字符串,则扩展失败,因为单词被解释为变量,没有中间算术运算符,这是一个错误。 This is what you see. 这就是你所看到的。

What you probably want, is replace the line value=$[${CfgData[$COUNTER]}] with value=${!CfgData[$COUNTER]} . 你可能想要的是用value=${!CfgData[$COUNTER]}替换行value=$[${CfgData[$COUNTER]}]

Let me add that your script would probably be better written without the indices, like 让我补充一点,你的脚本可能会更好地编写没有索引,如

for varname in "${CfgData[@]}"; do
    value=${!varname}
    echo -ne "$varname=$value"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM