在 bash 脚本中迭代变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17319100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over variable name in bash script
提问by rafa
I needed to run a script over a bunch of files, which paths were assigned to train1, train2, ... , train20, and I thought 'why not make it automatic with a bash script?'.
我需要在一堆文件上运行一个脚本,这些文件的路径被分配给train1, train2, ... , train20,我想“为什么不用 bash 脚本让它自动?”。
So I did something like:
所以我做了类似的事情:
train1=path/to/first/file
train2=path/to/second/file
...
train20=path/to/third/file
for i in {1..20}
do
python something.py train$i
done
which didn't work because train$iechoes train1's name, but not its value.
这不起作用,因为train$iechoestrain1的名称,而不是它的值。
So I tried unsuccessfully things like $(train$i)or ${train$i}or ${!train$i}.
Does anyone know how to catch the correct value of these variables?
所以,我想失败的事情喜欢$(train$i)或${train$i}或${!train$i}。有谁知道如何捕捉这些变量的正确值?
采纳答案by Nikolai Popov
You can use array:
您可以使用数组:
train[1]=path/to/first/file
train[2]=path/to/second/file
...
train[20]=path/to/third/file
for i in {1..20}
do
python something.py ${train[$i]}
done
Or eval, but it awfull way:
或评估,但它可怕的方式:
train1=path/to/first/file
train2=path/to/second/file
...
train20=path/to/third/file
for i in {1..20}
do
eval "python something.py $train$i"
done
回答by glenn Hymanman
Use an array.
使用数组。
Bash does have variable indirection, so you can say
Bash 确实有可变的间接性,所以你可以说
for varname in train{1..20}
do
python something.py "${!varname}"
done
The !introduces the indirection, so "get the value of the variable named by the value of varname"
在!介绍了间接,因此“获得通过VARNAME的值命名变量的值”
But use an array. You can make the definition very readable:
但是使用数组。您可以使定义非常易读:
trains=(
path/to/first/file
path/to/second/file
...
path/to/third/file
)
Note that this array's first index is at position zero, so:
请注意,此数组的第一个索引位于零位置,因此:
for ((i=0; i<${#trains[@]}; i++)); do
echo "train $i is ${trains[$i]}"
done
or
或者
for idx in "${!trains[@]}"; do
echo "train $idx is ${trains[$idx]}"
done

