linux - 如何在for循环中调用变量作为变量名和变量值

标签 linux bash variables for-loop

我对 Linux 中的脚本编写相对较新(更习惯于使用 R),但我正在尝试执行一个脚本,在该脚本中我将一些变量设置为文件路径,然后我可以随后在 for 循环中调用它们,所以我可以调用两者脚本中的变量名和变量值。

例如,我将为命令的参数调用变量值(如在文件路径中),但对于命令的输出,我将调用变量名来写入输出。我试图使用下面的花括号来实现这一点。这行得通吗???

如有任何帮助,我们将不胜感激!

#Generate variables with path directories
C1=/path/file1
C2=/path/file2
C3=/path/file3
C4=/path/file4
L1=/path/file1
L2=/path/file2
L3=/path/file3

#Loop through each instance of C for each instance of L (to create L*C number of outputs)
for Cid in C1, C2, C3, C4,
do for Lid in L1, L2, L3,
do
commandA -arg1 $${Cid} -arg2 $${Lid} -output /path/file${Cid}${Lid}
done
done

最佳答案

这是用declare -A声明的关联数组的工作:

#!/usr/bin/env bash

declare -A arr=(
[C1]=/path/file1
[C2]=/path/file2
[L1]=/path/file1
[L2]=/path/file2
)

for index in "${!arr[@]}"; do
    echo "$index:${arr[$index]}"
done
  • ${!arr[@]}:数组的所有索引(C1, C2, ...)
  • ${arr[$index]}:给定索引对应的数组元素(/path/file1, ...)

如果你想坚持使用常规变量,你可以使用variable indirection :

C1=/path/file1
C2=/path/file2
L1=/path/file1
L2=/path/file2

for var in C1 C2 L1 L2; do
    echo "$var:${!var}"
done

${!parameter}

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

关于linux - 如何在for循环中调用变量作为变量名和变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371938/

相关文章:

git - 如何在 gitrevisions <text> 中使用大括号扩展

php - Symfony 2/Doctrine - 始终可用的数据库连接?

matlab - 如何将变量移入和移出类似于 MATLAB 中的 LOAD 和 SAVE 的结构?

linux - 主机无法 ping 通虚拟机 guest

linux - vim自动选择服务器名

bash - Cygwin程序已编译但无法运行

javascript - 不能在 fetch api 中使用变量

python - 无法从源代码安装 python 包

linux - 如何编写bash代码将一些内容输入文件并保存文件?

bash - 打印包依赖树