下面是我正在運行的腳本
#!/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
該腳本應該在兩種 env 條件下運行,但它只在 prod 中運行一次,在 stage 中運行三次。我哪里出錯了,任何指示或建議將不勝感激
uj5u.com熱心網友回復:
您需要為回圈使用與初始陣列不同的變數。否則,您將在第一次迭代期間覆寫陣列。
在這里,我為陣列和回圈變數使用了不同的變數:
#!/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
uj5u.com熱心網友回復:
陣列和標量引數位于同一個命名空間中,因此在此示例中標量將覆寫陣列:
$ a=(hello world)
$ a=123
$ echo "${a[@]}"
123
在您的示例中,您覆寫了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'
...
考慮以下:
$ a="hello"; echo "${a[@]}"
hello
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/346035.html
