- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我对 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 (!
), andparameter
is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest ofparameter
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 ofparameter
itself.
关于linux - 如何在for循环中调用变量作为变量名和变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371938/
我是一名优秀的程序员,十分优秀!