outtoexplore outtoexplore - 1 year ago 170
Bash Question

bash - Capture exit code from remote ssh command

I'm looking at capturing the exit status of a remote ssh command within a shell script
I have a shell script as follows :

function rSSH {
local x
echo "Running ssh command"
x=$(ssh -o StrictHostKeyChecking=no -i $keyPair -o ProxyCommand="ssh -W %h:%p -i $keyPair user@$bastionIP 22" user@$IP "$cmd")

echo "SSH status is : $x"
if [ $x -eq 0 ];then
echo "Success"

echo "Failure"
exit 1

exit 0

When I execute the above script as a background job with an invalid $bastionIP( testing failure scenario), it results with an exit code of 0 ( instead of 1) and the only information I see in the logs is the first echo "Running ssh command" and it just exits the script.

Can someone point out what I'm doing wrong or a better way to capture the exit status of the remote ssh command.
Appreciate any help.

Answer Source

The script appears to be running under set -e, which means when the ssh connection fails, the script exits immediately.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download