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

标签 linux bash shell

下面是我正在运行的脚本

#!/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

我得到的输出是

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

但我的期望是得到

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

脚本应该在两种环境条件下运行,但它只在生产环境中运行一次,在舞台环境中运行三次。 我哪里出错了,任何指示或建议将不胜感激

最佳答案

您需要为循环使用与初始数组不同的变量。否则,您将在第一次迭代期间覆盖数组。

这里我为数组和循环变量使用了不同的变量:

#!/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

输出:

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

PS:另一种选择是使用一串多个单词并让 bash 对其进行迭代:

for a in foo bar
do
    for b in baz qux
    do
        echo "${a}"
        echo "${b}"
    done
done

关于linux - 在 bash 脚本中一次运行多个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69808565/

相关文章:

linux - Bash:为什么我不能为变量分配绝对路径?

linux - 如何使ffmpeg将其输出写入命名管道

linux - 配置中的 Endian 属性。文件

node.js - 如何将命令传递到 screen session ?

bash - 将 gzip 压缩的 CSV 连接到一个转义 header 中

shell - 如何从 Windows shell 访问 docker VM (MobyLinux) 文件系统?

linux - 没有元数据的 tar 存档

linux - 使用 -L 如何影响链接器?

linux - 为什么这个 shell 脚本不起作用?

linux - 根据内容将巨大的哈希文件分成一个文件(shell脚本)