Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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?

like image 216
pQB Avatar asked May 30 '12 16:05

pQB


People also ask

What is $_ in shell script?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What does ${} mean in shell script?

Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.


1 Answers

You need to utilize Variable Indirection:

SAMPLE1='1-first.with.custom.name' SAMPLE2='2-second.with.custom.name'  for (( i = 1; i <= 2; i++ )) do    var="SAMPLE$i"    echo ${!var} done 

From the Bash man page, under 'Parameter Expansion':

"If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion."

like image 183
johnshen64 Avatar answered Oct 13 '22 10:10

johnshen64