Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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. Where am I going wrong here, any pointers or advice would be appreciated

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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

PS: Another option would be to use a string of multiple words and have bash iterating over that:

for a in foo bar
do
    for b in baz qux
    do
        echo "${a}"
        echo "${b}"
    done
done
over 4 years ago · Santiago Trujillo Relatório

0

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:

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
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda