【问题标题】:Why does my if statement evalute my variable as empty? [duplicate]为什么我的 if 语句将我的变量评估为空? [复制]
【发布时间】:2020-12-31 00:06:10
【问题描述】:

我正在尝试创建一个 Bash 脚本来创建一个 AWS EC2 实例。

目标:提高我的 Bash 脚本技能

为了提高我的 bash 脚本编写技能,我想练习在我的脚本中创建 if 语句。 如上所示,我创建了 if 语句来检查变量 new_ami 是否为空,然后回显“未找到它”,但如果它不为空,它将回显“找到 AMI”。

这是我的脚本

ami=$(aws ec2 describe-images --owners self amazon --filters "Name=name, Values=amzn2-*.0-x86_64-gp2" "Name=state, Values=available" --profile XXXXXX --output json | jq '.Images | sort_by(.CreationDate) | last(.[]).ImageId')

new_ami=$(echo "${ami}" | sed 's/"//g')

echo $new_ami

if test -z "$new_ami"
then
    echo "Found AMI"
else
    echo "Did not find it"
fi

当我运行我的脚本时,这是结果,我得到了

ami-0ce1e3f77cd41957e
Did not find it

我有一个问题:

  1. 脚本回显变量 new_ami,这表明变量不为空,但 if 语句未能回显“找到 AMI”,而是回显“未找到”,这意味着变量 new_ami 为空。 这怎么可能发生? 为什么我的 if 语句会这样? 我如何解决它? 感谢您的所有帮助

【问题讨论】:

  • -z "$new_ami" 如果变量的长度为零(即变量未定义或没有值),则计算结果为 true;在then/else 块之间切换你的echo 命令,你应该很高兴

标签: bash amazon-web-services amazon-ec2


【解决方案1】:

@davidonstack if test -z "$new_ami" 返回 false,因为它检查变量是否有长度。

所以当它的-z返回true时,则执行表达式,如果为false则执行else表达式。

man test查看更多信息

-z string     True if the length of string is zero.
-n string     True if the length of string is nonzero.

尝试如下使用-n

ami=$(aws ec2 describe-images --owners self amazon --filters "Name=name, Values=amzn2-*.0-x86_64-gp2" "Name=state, Values=available" --profile XXXXXX --output json | jq '.Images | sort_by(.CreationDate) | last(.[]).ImageId')

new_ami=$(echo "${ami}" | sed 's/"//g')

echo $new_ami

if test -n "$new_ami"
then
    echo "Found AMI"
else
    echo "Did not find it"
fi

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 2015-12-07
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多