0

I have the below requirement to concatenate the value of a variable to its own variable and create one array:

Table=CRS
Job=JOBNAME
gen_job_$Table=GENERATEDJOB
gen_job_$TABLE=$Job,${gen_job_${Table}}
echo ${gen_job_${Table}} should give JOBNAME,GENERATEDJOB

I tried using the eval function also as below:

eval gen_job_$Table=$job,eval echo \$gen_job_$Table

However, I am not able to display the final result.

2
  • In the line gen_job_$Table=GENERATEDJOB, are you using a dollar sign inside a variable name? I don't actually know if that's valid. I tried it, and was given an error. Commented Sep 10, 2017 at 10:27
  • You can do something similar with indirection, e.g. var1=10; a=1; str=var$a; echo ${!str} Output is 10 Commented Sep 10, 2017 at 11:00

1 Answer 1

1

You perhaps just want to consider using an array for a situation like this (and I recommend reading this page, however, if you want to dynamically build your variable names it is possible. To set a variable whose name is stored in another variable use printf -v like

table=CRS
job=JOBNAME
holds_name="gen_job_$Table"
printf -v "$holds_name" 'GENERATEDJOB'

Then when you want to access the variable whose name is set in holds_name you can use indirection:

printf '%s,%s\n' "$job" "${!holds_name}"

Using braces around the variable name, if the first character inside the brace is ! then the rest of the word is treated as the name of a variable that is expanded to find the name of the actual variable whose value should be used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.