0

I'm trying to create variables from array elements and check value of my created variable in sourcefile.

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.

3
  • you can use regex to get if the array members are numbers or contain any other letters. Commented Nov 6, 2013 at 18:03
  • Still I want to get all values. Not filter out those which doesn't contain numbers. Or did I misunderstood you ? Commented Nov 6, 2013 at 18:11
  • with regex you can get result but at the same time you can have the items in the array as it was... you can check the output of regex to get if it not contain number. Commented Nov 6, 2013 at 18:15

1 Answer 1

2

First, the $[...] bash syntax is obsolete and should not be used.

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. 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]}.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.