AWS EKS CLI 命令 - if/else 不工作

AWS EKS CLI command - if/else not working

我正在尝试做一个基本的 if/else 来检查集群是否已经存在,然后再创建另一个同名的集群。这是整个部分;

 cluster=$(aws eks list-clusters | jq -r ".clusters" | grep mycluster_test)
 
 if [ $? -eq 0 ]; then
     echo "this worked, the cluster is $cluster"
 else
     echo "no cluster by this name"
 fi

没有这个名字的集群,当我运行脚本时它returns什么都没有。但我不明白为什么它不返回 else 语句

我确实有一个名为 'mycluster_new' 的集群,当我为此 grep 时,返回了第一个 echo 语句,请问我可以得到帮助,了解为什么 else 语句是失败。谢谢

试试这个

如果你的变量是字符串

if [[ $cluster == 1 ]]; then

如果你的变量是整数

if [[ $cluster -eq 1 ]]; then

设法通过检查字符串是否为空来解决此问题,运行无论是否为空都会继续进行检查。

CLUSTER=my_eks_cluster

CHECK_NAME=$(aws eks list-clusters | jq -r ".clusters" | grep $CLUSTER || true)

然后 运行 检查一下;

    if [ "$CHECK_NAME" != "" ]; then
        echo "There is already a cluster by this name; $CHECK_NAME. Cannot build another"
        exit 1
    else
        echo "No cluster by this name $CLUSTER, will continue with terraform"
    fi

如果你真的想继续你的老方法,你总是可以使用'-z'来检查字符串是否为空

 if [ -z "$cluster" ]; then
     echo "this worked, the cluster is $cluster"
 else
     echo "no cluster by this name"
 fi