15

I am running a script from remote machine via ssh:

ssh 'some_cmd;my_script'  

Now, I want to store exit status of shell script on my local machine. How can I do it?

2
  • 1
    Could you explain some more details? The command is started from remote and running on local? Commented Jun 8, 2016 at 11:35
  • 2
    from man ssh: EXIT STATUS ssh exits with the exit status of the remote command or with 255 if an error occurred. Commented Jun 8, 2016 at 12:28

2 Answers 2

29

Assuming nothing goes wrong with ssh itself, its exit status is the exit status of the last command executed on the remote host. (If something does go wrong, its exit status is 255.)

$ ssh remotehost exit 13
$ echo $?
13
Sign up to request clarification or add additional context in comments.

7 Comments

Formally, to "store" the exit status we should assign it to a variable: ssh remotehost 'do something' ; retcode=$? and it's "stored" in $retcode
I am not sure where the author got that list; it's not in the man page on the machines I've checked. Part of the problem is that the exit status is ambiguous in this situation: did ssh itself have a problem, or did the program that ssh ran have one of those exit statuses?
Indeed ... this just doesn't cater well for the corner case where the remote exit code equals 255 .... other than that a great answer :)
This is not true for the ssh client coming with FreeBSD 11.1.
This did not work for me on macOS 12.6.2 with SSH version: ssh -V: OpenSSH_8.6p1, LibreSSL 3.3.6.
|
1

I had same problem. I don't think the previous answers will work (at least, they did not work for me).

This is what worked for me: I ran my command and displayed the exit code and captured it in a variable.

Ensure you protect the $? sign with the escape sequence, \:

# retcode=$(ssh [email protected] "grep -q test /etc/passwd ; echo \$? " 2>/dev/null)
# echo $retcode
# 1

Comments

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.