Home > Net >  looping with if and for but not getting expected output
looping with if and for but not getting expected output

Time:05-19

I am writing a bash script as below, which runs and giving me output as below.

Output:

4
3

But my expected output is as below. Can someone point me where I am going wrong. Thanks in advance.

1
2
3
4
#!/bin/bash

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

for regions in "${region[@]}"; do

for env in "${envs[@]}"; do

if [ "${regions[*]}" == "eu-central" ] && [[ "${env[*]}" == "stage" ]]; then

echo 1

elif [ "${regions[*]}" == "eu-central" ] && [[ "${env[*]}" == "prod" ]]; then

echo 2

elif [ "${regions[*]}" == "us-east-1" ] && [[ "${env[*]}" == "stage" ]]; then

echo 3

elif [ "${regions[*]}" == "us-east-1" ] && [[ "${env[*]}" == "prod" ]]; then

echo 4

fi
done
done

CodePudding user response:

  1. You're comparing against eu-central but the array includes eu-central-1
  2. You're not using the loop variables, instead off "${regions[*]}" just use "$regions"
  3. Proper indent your script

Applying the above gives us:

#!/bin/bash

for regions in "${region[@]}"; do
    for env in "${envs[@]}"; do
        if [ "$regions" == "eu-central-1" ] && [[ "${env[*]}" == "stage" ]]; then
            echo 1
        elif [ "$regions" == "eu-central-1" ] && [[ "$env" == "prod" ]]; then
            echo 2
        elif [ "$regions" == "us-east-1" ] && [[ "$env" == "stage" ]]; then
            echo 3
        elif [ "$regions" == "us-east-1" ] && [[ "$env" == "prod" ]]; then
            echo 4
        fi
    done
done

2
1
4
3

Try it online!

  • Related