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.

3
  • What do you want to do with this? Commented Oct 31, 2016 at 16:22
  • Why do you think you need "delayed expansion" in Bash? Commented Oct 31, 2016 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? Commented Oct 31, 2016 at 17:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is bash 4.0 and greater, right?
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?
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.
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+

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.