2

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")

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

   else
      echo "Failure"
      exit 1
   fi
}

rSSH
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.

2
  • 2
    Are you using set -e? Commented Aug 6, 2016 at 0:12
  • ahh yeah. That's probably causing the issue. @chepner Thanks for pointing that out. Totally missed that Commented Aug 7, 2016 at 4:54

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

Faced the same issue. I had to execute a bunch of commands over a remote ssh connection as below and the script will terminate before the 'echo'ing the 'return here='.

ssh -v -T -i ${KEY} -p${PORT} -tt ${USER}@${IP} /bin/bash -c "'
echo "Inside Script"
exit 12
'"
echo "return here=$?"

Thanks to the response of @chepner in the original post, it was the same issue that I was using set -e

Removing it helped to resolve.

Comments

-1

Try using another variable for return code.

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")

   local ret_code
   ret_code=$?
   echo "SSH status is : $ret_code"
   if [ $ret_code -eq 0 ];then
      echo "Success"

   else
      echo "Failure"
      exit 1
   fi
}

rSSH
exit 0

3 Comments

Why do you the variable name x is problematic? You should then change the local too.
You can keep the local.
You need to update it to also declare ret_code as local.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.