如何使用shell脚本在if else块中ssh到虚拟机?

ilmyapht  于 2023-03-13  发布在  Shell
关注(0)|答案(1)|浏览(173)

如何使用shell脚本在if else块中ssh到虚拟机?

docker build -t qtech/security-categories-microservice:latest .
docker run -d --name sec-cat-ms qtech/security-categories-microservice:latest
sleep 10
status=$(docker ps | grep sec-cat-ms | awk '{print $1}')
echo "$status"
if   [ "$status" != "" ]; then
        docker push qtech/security-categories-microservice:latest      

        ssh -i ip.pem -o "StrictHostKeyChecking no" -tt root@xx.xx.xx.xx <<-'EOF'
        ./refresh.sh
        sleep 10
        docker service ls
        docker ps
        exit
        EOF

        pwd
        docker rm -f sec-cat-ms
        docker rmi -f $(docker images qtech/security-categories-microservice -q)
        sleep 5
         
elif [ "$status" = "" ]; then
        docker logs sec-cat-ms &> Security-Categories-MicroService-Error-Logs.txt &
        docker rm -f sec-cat-ms
        docker rmi -f $(docker images qtech/security-categories-microservice -q)
        exit 1
fi

在尝试执行此代码时,bash抛出以下错误消息。

Syntax error: end of file unexpected (expecting "fi")

我们确实使用fi关闭了if块,但它仍然抛出上述错误消息。
我们正在运行Jenkins shell作业中的代码
那么,如何使用shell脚本在if else块中ssh到虚拟机中呢?

tez616oj

tez616oj1#

Shellcheck.net - 反复使用它,每次你的脚本出现问题。
一些简单的例子模板-

#!/bin/bash

if true
then echo simple quotes
     ssh localhost '
         date
         sleep 2
         date
     '
fi

if true
then echo SIMPLE here-doc with creative spacing
     ssh localhost <<_____EOT
         date; sleep 2
         date
_____EOT
fi

if true
then echo here-string
     ssh localhost <<< 'date; sleep 2; date'
fi

if true
then echo piped input
     echo '
         date
         sleep 2
         date
     ' | ssh localhost
fi

引号可能很重要,这取决于在命令列表中嵌入了什么(以及如何嵌入)。

相关问题