简体   繁体   English

Unix Shell脚本-在另一个变量内替换变量并将值连接到同一变量

[英]Unix shell script - variable substitution inside another and concatenate values to the same variable

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函数,如下所示:

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

However, I am not able to display the final result. 但是,我无法显示最终结果。

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 您可能只想考虑在这种情况下使用数组(我建议阅读此页面 ,但是,如果要动态构建变量名,则可以这样做。要设置名称存储在另一个变量中的变量,请使用printf -v喜欢

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: 然后,当您要访问其名称在holds_name设置的变量时,可以使用间接holds_name

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. 那么该词的其余部分将被视为变量的名称,该变量将展开以查找应使用其值的实际变量的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM