Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:


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

I would expect the output:


but i got:


Is it possible generate var names in the fly?

share|improve this question
up vote 5 down vote accepted

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


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

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

share|improve this answer
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 at 16:24

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

for (( i = 1; i <= 2; i++ ))
  echo ${!NEW_NAME}
share|improve this answer

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
share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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