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?


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.


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

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.


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 $?'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.