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?

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

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

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.