Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash "delayed expansion" and nested variables [duplicate]

Tags:

bash

I was able to do the following in batch, but for the life of me, I cannot figure out how to do this in bash and could use some help. Basically, I used a for loop and delayed expansion to set variables as the for loop iterated through an array. It looked something like this:

FOR /L %%A in (1,1,10) DO (
   SET someVar = !inputVar[%%A]!
)

The brackets are merely for clarity.

I now have a similar problem in bash, but cannot figure out how "delayed expansion" (if that's even what it is called in bash) works:

for (( a=1; a<=10; a++ )); do
   VAR${!a}= some other thing
done

Am I completely off base here?

Update:

So it seems that I was completely off base and @muru's hint of the XY problem made me relook at what I was doing. The easy solution to my real question is this:

readarray -t array < /filepath

I can now easily use the needed lines.

like image 476
ahchoo4u Avatar asked Sep 17 '25 22:09

ahchoo4u


1 Answers

I think, that eval could help in this case. Not sure, if it's the best option, but could work.

INPUT_VAR=(fish cat elephant)
SOME_VAR=

for i in `seq 0 3`;do
    SOME_VAR[$i]='${INPUT_VAR['"$i"']}'
done

echo "${SOME_VAR[2]}"        # ${INPUT_VAR[2]}
eval echo "${SOME_VAR[2]}"   # elephant

Nice eval explanation: eval command in Bash and its typical uses

Working with arrays in bash, would be helpful too: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

Note, that arrays are supported only at new version of bashs.

like image 117
Jan Avatar answered Sep 19 '25 12:09

Jan