为什么我的if语句将我的变量求值为空



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

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

为了提高我的bash脚本技巧,我想练习在脚本中创建if语句。如上所示,我创建了if语句来检查变量new_ami是否为空,然后返回";没有找到它";但如果它不是空的,它将回声"0";Found 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语句未能回显"Found AMI";相反,它呼应";没有找到它";这意味着变量new_ami为空。这怎么会发生?为什么我的if语句会这样?我该怎么修?谢谢你的帮助

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

因此,当其-z返回true时,表达式将被执行,如果为false,则表达式将执行。

查看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

最新更新