【问题标题】:SSH not exiting properly inside if statement in bash heredocSSH 在 bash heredoc 中的 if 语句中没有正确退出
【发布时间】:2021-03-10 09:00:12
【问题描述】:

所以我正在运行这个脚本来通过 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

【问题讨论】:

  • 通过在 HEREDOC 中发出 exit,您将退出 ssh 会话,因此永远不会进入 ./other_script.sh 部分。应该退出回到本地环境而不是远程环境
  • 我尝试过类似“exit &”的方法,但这让我回到了远程环境。您对如何处理退出 ssh 有什么建议吗?
  • 将此脚本放在另一个脚本中,当 java 未运行时,以数字退出。然后当ssh退出时,可以查看脚本中的退出代码,必要时运行other_script
  • 在 bash 中看起来如何?在 heredoc 之外,我是否使用 if 语句来检查退出代码? (目前在另一个脚本中,只是其中的一部分)
  • 是的,确实.....

标签: bash ssh eof heredoc


【解决方案1】:

出口正在退出 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

【讨论】:

  • 谢谢!!我必须做的唯一改变是在 if 语句中使用 -eq 而不是 ==
猜你喜欢
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多