5

I'm trying to generate dynamic var names in a shell script to process a set of files with distinct names in a loop as follows:

SAMPLE1='1-first.with.custom.name'
SAMPLE2='2-second.with.custom.name'

for (( i = 1; i <= 2; i++ ))
do
  echo SAMPLE{$i}
done

I would expect the output:

1-first.with.custom.name
2-second.with.custom.name

but i got:

SAMPLE{1}
SAMPLE{2}

Is it possible generate var names in the fly?

5

Why not use an array, they're meant for doing things like that.

sample[1]='1-first.with.custom.name'
sample[2]='2-second.with.custom.name'

for (( i = 1; i <= 2; i++ ))
do
  echo ${sample[$i]}
done

Also don't use all-capital variable names in your script to prevent accidentally using reserved variable names.

  • Mainly because that was the first idea coming to my mind and needed quickly do a test. Arrays are more flexible and I will take them into account for future works – pQB May 31 '12 at 7:22
  • arrays don't work on bash 3 (which is on my macbook for example) – mazs Feb 24 '16 at 16:24
5

I found that I can get the expected results as follows:

for (( i = 1; i <= 2; i++ ))
do
  NEW_NAME=SAMPLE$i
  echo ${!NEW_NAME}
done
3

If you want to do it using portable, POSIX standard shell and avoid bash extensions like arrays, you need to use eval:

$ foo1='a b c'
$ foo2='d e f'
$ a=1; eval echo \$foo$a
a b c
$ a=2; eval echo \$foo$a
d e f
  • Actually, It is a test case for personal use but thanks for the advice on make it portable. – pQB May 31 '12 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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