Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

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.

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
add comment

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
share|improve this answer
add comment

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
add comment

Your Answer

 
discard

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.