Alex Rivera | Logout

How can I generate new variable names on the fly in a shell script?

Asked 2012-05-30T16:25:53.887
41

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:

#!/bin/bash

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?

Edit
Report

1 Answer

3

Not as far as I know, They way @johnshen64 said. Also, you could solve your problem using an array like so:

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

Note that you don't need to use numbers as indexes SAMPLE[hello] will work just as well

answered 2012-05-30T16:34:07.737

Your Answer