0

I have a script (on my local machine). In the script, a connection is established via ssh to a slave machine and it runs a build script on the slave:

ssh $user@$slave_ip bash $dest_root/$dest_dir/slave_run

Is there a way to capture the exit code that is returned from the slave_run script in a parent script variable?

  • possible duplicte [https://unix.stackexchange.com/questions/66581/bash-shell-ssh-remote-script-capture-output-and-exit-code](https://unix.stackexchange.com/questions/66581/bash-shell-ssh-remote-script-capture-output-and-exit-code) – Raph Peres Sep 12 '17 at 06:36
  • That's IMHO not a duplicate question, but shows you how to do it. – Kusalananda Sep 12 '17 at 08:37

2 Answers2

0

To examine the exit code, you need to examine a special variable which is "$?" This variable tell's you the exit code of the last command you ran.

ssh $user@$slave_ip 'bash $dest_root/$dest_dir/slave_run ; echo $?'
Hunter.S.Thompson
  • 8,839
  • 7
  • 26
  • 41
0

Your command (with added double quotes):

ssh "$user@$slave_ip" bash "$dest_root/$dest_dir/slave_run"

The capture the exit code will be in $? after the execution of that command.

Example:

$ ssh someserver sh -c 'false'
$ echo $?
1

To capture it:

$ ssh someserver somecommand
$ code=$?

Alternatively, get the command on the server to output the exit code and capture it as a string:

$ code=$( ssh server sh -c "somecommand; echo \$?" )

In your case:

$ code=$( ssh "$user@$slave_ip" sh -c "$dest_root/$dest_dir/slave_run; echo \$?" )

It's necessary to escape the $ of $? as the command is within double quotes and we'd like $? to be evaluated by the shell on the server side, not by the shell on the client.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936