Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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,我需要在一堆文件上运行一个脚本,这些文件的路径被分配给train1,train2第20列,我想‘为什么不用bash脚本使它自动?’ 所以我做了一些类似的事情: 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 这不起作用,因为train$i回显train1的名称,

我需要在一堆文件上运行一个脚本,这些文件的路径被分配给
train1
train2
<代码>第20列,我想‘为什么不用bash脚本使它自动?’

所以我做了一些类似的事情:

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
这不起作用,因为
train$i
回显
train1
的名称,但不回显其值

所以我尝试了一些失败的方法,比如
$(train$I)
或者
${train$I}
或者
${!train$I}
。 有人知道如何捕捉这些变量的正确值吗?

您可以使用数组:

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
或评估,但它完全是:

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
使用数组

Bash确实有变量间接寻址,所以可以这样说

for varname in train{1..20}
do
    python something.py "${!varname}"
done
引入了间接寻址,因此“获取由varname的值命名的变量的值”

但是使用数组。您可以使定义非常可读:

trains=(
    path/to/first/file
    path/to/second/file
    ...
    path/to/third/file
)
请注意,此数组的第一个索引位于零位置,因此:

for ((i=0; i<${#trains[@]}; i++)); do
    echo "train $i is ${trains[$i]}"
done

哦,我可以在每个文件名上使用python something.py,但是稍后我需要在相同的文件上运行一些其他脚本,这就是为什么我把它放在这些变量上谢谢!这个方括号结构是某种字典吗?@rafa这是获取数组元素引用的方法。更简单的是“${trains[@]}”中的火车的
。当然,数组变量名应该是复数:)
for idx in "${!trains[@]}"; do
    echo "train $idx is ${trains[$idx]}"
done