I need to create many variables that begin with "precip" followed by a dynamic string which is a read in variable. I read this variable in, let's say its "1971" and then I increment it by 5 a bunch of times to create five or so variables spanning the range from 1971, 1976, 1981, etc. I need to append each of these variables (named yr1, yr2, yr3...) to the the "precip" variable.
As an example, instead of the hard coded variables found below:
precip1971="pr_"$reg"_"$glob"_1971010103.nc"
precip1976="pr_"$reg"_"$glob"_1976010103.nc"
precip1981="pr_"$reg"_"$glob"_1981010103.nc"
precip1986="pr_"$reg"_"$glob"_1986010103.nc"
precip1991="pr_"$reg"_"$glob"_1991010103.nc"
precip1996="pr_"$reg"_"$glob"_1996010103.nc"I would like something like (knowing this below is wrong):
precip+yr1="pr_"$reg"_"$glob"_1971010103.nc"
precip+yr2="pr_"$reg"_"$glob"_1976010103.nc"
precip+yr3="pr_"$reg"_"$glob"_1981010103.nc"
precip+yr4="pr_"$reg"_"$glob"_1986010103.nc"
precip+yr5="pr_"$reg"_"$glob"_1991010103.nc"
precip+yr6="pr_"$reg"_"$glob"_1996010103.nc"so that precip+yr1 equals a variable named precip1971, precip+yr2 equals a variable named precip1976, and so on.
I have found ways to concatenate two variables' values, but not a new variable with the value of an existing variable.
Is there a way to do this in Bash?
Thanks.
31 Answer
You can use eval to evaluate the variable assignment. Below is a sample program related to your scenario.
#!/bin/bash
year=1971
for ((i=0; i<=10; i++))
do eval precip${year}="pr_${reg}_${glob}_1971010103.nc" ((year+=5))
doneHere the eval statement evaluates the variable precip${year} to precip1971 and so on.