Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash变量名是连接的结果_Bash - Fatal编程技术网

Bash变量名是连接的结果

Bash变量名是连接的结果,bash,Bash,我正在努力做到: declare -a array=(first second third) for i in ${array[@]}; do ${i}_arg=$(some commands here...) done 预期结果: first_arg=something1 second_arg=something2 third_arg=something3 如何实现这一点?我解决了在变量名前添加“export”的问题。不确定这是否是最好的方法。如果可能,放弃这种方法本身,改用关联数组。

我正在努力做到:

declare -a array=(first second third)
for i in ${array[@]}; do
  ${i}_arg=$(some commands here...)
done
预期结果:

first_arg=something1
second_arg=something2
third_arg=something3

如何实现这一点?

我解决了在变量名前添加“export”的问题。不确定这是否是最好的方法。

如果可能,放弃这种方法本身,改用关联数组。它们在Bash4中可用

declare -A args
arg[$i]=$(some commands here)

第一:除非您有非常令人信服的理由使用此数组而不是关联数组,否则不要使用。更适合作为最佳实践

第二:本主题将在中详细介绍。要总结此处给出的选项


您可以使用
typeset
(在bash、ksh或zsh中)或
declare
(在bash中):


您可以使用
printf-v
(在最近的bash中):


您可以使用
读取

IFS= read -r "${i}_arg" < <(some commands here...)

IFS=read-r“${i}\u arg”<这是一个注释,不是一个答案。这是一个答案,很好。不过,我建议使用
声明
而不是
导出
。@CharlesDuffy:我同意你的看法+1@Bastien974,…顺便说一句,解释一下为什么
declare
在这里比
export
更好——这是关于副作用的
export
还向流程环境添加了一个变量,由子级继承,而
declare
将其本地设置为shell(实际上,如果在函数内部,则本地设置为当前shell函数)。如果您不需要将某些内容导出给您的孩子,最好不要在他们的进程空间中浪费内存(环境变量与argv内容的有限存储空间相同)。
printf -v "${i}_arg" %s "$(some commands here...)"
IFS= read -r "${i}_arg" < <(some commands here...)