You are not logged in.

#1 2009-10-06 18:29:11

JSHN
Member
From: Sweden, Trollhättan
Registered: 2009-10-05
Posts: 12

[Solved] - Bash scripting - variable question.

Hi!

I have a little problem, I want to get data from a variable, but the variable-name that I want to
get the data from is constructed by another variable.

Let me explain with a little non-working example:

test1="data1"
test2="data2"
test3="data3"

for i in {1..3};do
        echo value=$[test$i];done

I want to get the output of this code to be:
value=data1
value=data2
value=data3
and I cannot use arrays in the script I'm working on. I know how to do this in other languages
but cannot figure it out how to do it in bash.

Please help! smile

Last edited by JSHN (2009-10-06 19:55:15)

Offline

#2 2009-10-06 19:16:49

Andrwe
Member
From: Leipzig/Germany
Registered: 2009-06-17
Posts: 322
Website

Re: [Solved] - Bash scripting - variable question.

Hi,
it should be like this:

test1="data1"
test2="data2"
test3="data3"

for i in {1..3};do
        echo value=${test}${i};done

Last edited by Andrwe (2009-10-06 19:17:16)


Website: andrwe.org

Offline

#3 2009-10-06 19:25:30

klixon
Member
From: Nederland
Registered: 2007-01-17
Posts: 525

Re: [Solved] - Bash scripting - variable question.

you need the eval command to finish how you started:

eval echo value=\$test$i

Otherwise, use bash arrays:

test=('data1' 'data2' 'data3')
for i in $(seq 0 2);do # zero-based...
  echo value=${test[$i]}
done

ninja-edit to remove the comma's in the array

Last edited by klixon (2009-10-06 19:27:03)


Stand back, intruder, or i'll blast you out of space! I am Klixon and I don't want any dealings with you human lifeforms. I'm a cyborg!

Offline

#4 2009-10-06 19:29:40

Garns
Member
Registered: 2008-05-28
Posts: 239

Re: [Solved] - Bash scripting - variable question.

Alternatively you could use variable indirection:

for i in {1..3}; do
  var="test$i"
  echo "value=${!var}"
done

Offline

#5 2009-10-06 19:54:39

JSHN
Member
From: Sweden, Trollhättan
Registered: 2009-10-05
Posts: 12

Re: [Solved] - Bash scripting - variable question.

I appreciate all your help everyone, thanks!

@klixon: eval was just what I was looking for, now I can finally continue! smile

Offline

Board footer

Powered by FluxBB