Search code examples
bashssheofheredoc

SSH not exiting properly inside if statement in bash heredoc


So i am running this script to check if a java server is up remotely by sshing into remote. If it is down, i am trying to exit and run another script locally. However, after the exit command, it is still in the remote directory.

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


Solution

  • The exit is exiting the ssh session and so never gets to the execution of the other_script.sh line in the HEREDOC. It would be better to place this outside of the script and actioned from the exit status of the HEREDOC/ssh and so:

    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