简体   繁体   English

在bash脚本中一次运行多个循环

[英]Running multiple loop at once in bash script

Below is the script that I am running下面是我正在运行的脚本

#!/bin/bash

region=('us-east-1' 'eu-central-1')
env=('prod' 'stage')


for region in "${region[@]}"
do
        for env in "${env[@]}"
        do
                echo "$region"
                echo "$env"
        done
done

The output that I am getting is我得到的输出是

us-east-1
prod
us-east-1
stage
eu-central-1
stage
eu-central-1
stage

But my expectation was to get但我的期望是得到

us-east-1
prod
us-east-1
stage
eu-central-1
prod
eu-central-1
stage

The script should run for both env conditions, but its running only once for prod and thrice for stage.该脚本应该在两种 env 条件下运行,但它只在 prod 中运行一次,在 stage 中运行三次。 Where am I going wrong here, any pointers or advice would be appreciated我哪里出错了,任何指示或建议将不胜感激

You need to use a different variable for the loop than the initial array.您需要为循环使用与初始数组不同的变量。 Otherwise you are overwriting the array during the first iteration.否则,您将在第一次迭代期间覆盖数组。

Here I'm using different variables for the array and the loop variable:在这里,我为数组和循环变量使用了不同的变量:

#!/bin/bash

regions=('us-east-1' 'eu-central-1')
envs=('prod' 'stage')
    
for region in "${regions[@]}"
do
    for env in "${envs[@]}"
    do
        echo "$region"
        echo "$env"
    done
done

Output:输出:

us-east-1
prod
us-east-1
stage
eu-central-1
prod
eu-central-1
stage

Arrays and scalar parameters lives in the same namespace, so the scalar will override the array in this example:数组和标量参数位于同一个命名空间中,因此在此示例中标量将覆盖数组:

$ a=(hello world)
$ a=123
$ echo "${a[@]}"
123

In your example you are overriding the env variable in the inner loop, the execution is the following, in pseudo code:在您的示例中,您覆盖了内部循环中的env变量,执行如下,以伪代码表示:

expand "${region[@]}" into 'us-east-1' 'eu-central-1'
set region 'us-east-1'
expand "${env[@]}" into 'prod' 'stage'
set env 'prod'
... echo ...
set env 'stage'
... echo ...
set region 'us-central-1'
expand "${env[@]}" into 'stage'
...

Consider the following:考虑以下:

$ a="hello"; echo "${a[@]}"
hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM