Concatenate a variable onto the end of another variable or string in Bash

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.

3

1 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))
done

Here the eval statement evaluates the variable precip${year} to precip1971 and so on.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like