用 if 和 for 循环但没有得到预期的输出
looping with if and for but not getting expected output
我正在编写一个 bash 脚本,如下所示,该脚本运行并给出如下输出。
输出:
4
3
但我的预期输出如下。有人可以指出我哪里出错了。提前致谢。
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
- 您正在与
eu-central
进行比较,但数组包含 eu-central-1
- 您没有使用循环变量,而是关闭了
"${regions[*]}"
只需使用 "$regions"
- 正确缩进您的脚本
应用以上内容得到:
#!/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!
我正在编写一个 bash 脚本,如下所示,该脚本运行并给出如下输出。
输出:
4
3
但我的预期输出如下。有人可以指出我哪里出错了。提前致谢。
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
- 您正在与
eu-central
进行比较,但数组包含eu-central-1
- 您没有使用循环变量,而是关闭了
"${regions[*]}"
只需使用"$regions"
- 正确缩进您的脚本
应用以上内容得到:
#!/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