Bash variable within variable

Hello,
Can I ask how to expand variable that contains another in bash? I need to loop variable within another one like this:

RD1=testgrp
RD2=testgroup
RD3=testgroupfile
RD4=tstgroup
...
RD40=try2013

DEST=/home/king/finaldir

for i in {1..40}; do 
mv ${RD${i}}  ${DEST}
done

I do not want use array as for i in testgrp testgroup testgroupfile tstgroup try2013 as the list is too long.
Thanks a lot!

The best thing would be to use arrays:

RD[1]=testgrp
RD[2]=testgroup
RD[3]=testgroupfile
...
DEST=/home/king/finaldir
for i in {1..40}; do 
  echo mv "${RD}"  "${DEST}"
done
1 Like

Thanks! I did not think about using array with subscription. This is what I need! Thanks again!

While "indirecting" variables in shells usually is a bit delicate, in above case you could try

for i in $RD{1..4}; do echo $i; done
testgrp
testgroup
testgroupfile
tstgroup

, assuming you are using a recent bash .

2 Likes

Ah, This is what I was trying, but missed the part $RD{1..4}
Yes, I'm using bash. Thank you!

For future reference, If you do need indirection and you can use man bash (linux)

$ X=foo
$ Y=X
$ echo ${Y}
X
$ echo ${!Y}
foo
1 Like

Came across a more complicate scenario on top the previous post by looping two layers:

for I in 1{01..32} 20{0..9}
do 
for J in A1 A2 B1 B2
mkdir -p DES_P${I}${J}
cp SRC_P${I}${J} DES_P{I}${J}
# cp ${!SRC_P${I}${J}} ${!DES_P{I}${J}}               # Did not work:  -Bash: ${!SRC_P${I}${J}}: bad substitution
done
done

There are 168 folders. All the SRC_P${I}${J} were manually collected and defined from different folders (irregular, not even easy to do by regex) like:

SRC_P101A1=/home/apple/201310512/finished/Summary
SRC_P101A2=/home/orange/201311511/second_try/redo
etc
......

How to loop through the two layers and make the destination folders organized nicer and for easier peek-into in the future? Or am I thinking the wrong way? Thanks!

You can reduce the two loops by one loop,
and the ! must prefix the bare variable name.

for I in P{{101..132},{200..209}}{A1,A2,B1,B2}
do
 echo cp "SRC_${!I}" "DES_${!I}"
done

---------- Post updated at 07:19 PM ---------- Previous update was at 07:05 PM ----------

The following assembles new variable names first, so their bare names can be used:

...
do
 SRC="SRC_$I"; DES="DES_$I"
 echo cp "${!SRC}" "${!DES}"
done
1 Like

echo cp "SRC_${!I}" "DES_${!I}" but SRC_${!I} did not expand as wanted.
Must remember this way! assembles new variable names first, so their bare names can be used!
Thanks a lot!