1

This question already has an answer here:

I am trying to echo some values using a for loop.

hwEventType.txt contains this :

11000
11002
11004
11006
13025
13026

Code :

for event in $(cat /path/hwEventType.txt)
do
eval miny_"$event"_2001=`cut -f4 -d"|" /path/G_2001_DCC_ErrorCode_STAT_"$event"_"$filedate1".txt | sort -n | head -1`
done

filedate1 is today's date

files G_2001_DCC_ErrorCode_STAT_"$event"_"$filedate1".txt contains below information:

20180205 2356|2001|11000|24034
20180205 2357|2001|11000|24441
20180205 2358|2001|11000|25039
20180205 2359|2001|11000|24637
20180206 0000|2001|11000|24795
20180206 0001|2001|11000|23979
20180206 0002|2001|11000|24081
20180206 0003|2001|11000|24103
20180206 0004|2001|11000|23634
20180206 0005|2001|11000|23926

I want to perform the below :

for event in $(cat /path/hwEventType.txt); do echo "$minx_$event_2001"; done

But I got empty lines.

Is there any way to use a variable contains in its name a variable?

marked as duplicate by Andy Dalton, Wouter Verhelst, G-Man, Kusalananda, jayhendren Feb 8 '18 at 23:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

To possible ways to achieve this:

  • using a intermediate variable name :

    for event in $(cat /path/hwEventType.txt); do echo myvar="minx_$event_2001"; echo ${!myvar}; done

  • use a table to store / retrieve things instead of separate variables in your loops:

    miny[$event]=$(cut -f4 - ... )

and then

echo ${miny[$event]}

Not the answer you're looking for? Browse other questions tagged or ask your own question.