首页 > 解决方案 > SSH 在 bash heredoc 中的 if 语句中没有正确退出

问题描述

因此,我正在运行此脚本以通过 ssh 进入远程来检查 java 服务器是否已远程启动。如果它关闭,我正在尝试退出并在本地运行另一个脚本。但是,在退出命令之后,它仍然在远程目录中。

ssh -i ec2-user@$DNS << EOF
    
    if !  lsof -i | grep -q java ; then
        echo "java server stopped running"
        # want to exit ssh
        exit
        # after here when i check it is still in ssh
        # I want to run another script locally in the same directory as the current script
        ./other_script.sh
    else
        echo "java server up"

    fi;
EOF

标签: bashssheofheredoc

解决方案


exit 正在退出 ssh 会话,因此永远不会执行 HEREDOC 中的 other_script.sh 行。最好将其放置在脚本之外并从 HEREDOC/ssh 的退出状态中执行操作,因此:

ssh -i ec2-user@$DNS << EOF

if !  lsof -i | grep -q java ; then
    echo "java server stopped running"
    exit 7   # Set the exit status to a number that isn't standard in case ssh fails
else
    echo "java server up"
fi;
EOF
if [[ $? -eq 7 ]]
then
    ./other_script.sh
fi

推荐阅读