4

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.

ahchoo4u
  • 61
  • 1
  • 5
  • [What do you want to do with this?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – muru Oct 31 '16 at 16:22
  • Why do you think you need "delayed expansion" in Bash? – Ruslan Osmanov Oct 31 '16 at 16:23
  • @muru In short, I need to sort a csv. I am trying to use a for-loop to simultaneously set each line as an array and a numbered variable. e.g. `declare -a row#variable$n=awk 'NR==$n' /filepath` Does this clarify? – ahchoo4u Oct 31 '16 at 17:17

1 Answers1

3

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.

Community
  • 1
  • 1
Jan
  • 70
  • 8
  • This is bash 4.0 and greater, right? – ahchoo4u Oct 31 '16 at 16:42
  • So, to make sure I'm understanding you correctly, the echo without "eval" will only display "${SOME_VAR[2]}" as a string, whereas, eval will display the actual variable? – ahchoo4u Oct 31 '16 at 16:47
  • Not really, I didn't choose variable names too much well as I can now see. The `${SOME_VAR[2]}` is variable expansion, in this case it is value invariable SOME_VAR on index 2 (same as standard $VAR_NAME). There is placed string "${INPUT_VAR[2]}". If you want to expand that string and use as variable, eval will serve to you - evaluate normal string "${SOME_VAR[2]}" as variable, which in combination with echo shows content of $SOME_VAR on index of 2. – Jan Nov 01 '16 at 09:30
  • OK, I red it correctly once again and yes. It's exactly like that. In `${SOME_VAR[2]}` is string as variable name and if you want to use that string as variable, `eval` will server to you. Also looks, that support is for bash 4.0+ – Jan Nov 01 '16 at 09:45