You are not logged in.
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!
Last edited by JSHN (2009-10-06 19:55:15)
Offline
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
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
Alternatively you could use variable indirection:
for i in {1..3}; do
var="test$i"
echo "value=${!var}"
done
Offline
I appreciate all your help everyone, thanks!
@klixon: eval was just what I was looking for, now I can finally continue!
Offline