Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture exit code for remote script?

Tags:

bash

ssh

I have a shell script that runs on my server every day. It does some house cleaning and connects to a remote host to perform other tasks i.e.

#!/bin/bash

#do something...
...locally...

#run remote script...
ssh user@remotehost "/opt/process/verify.sh"

exit

It works fine but to be safe I would like to capture (if possible) the return code from "/opt/process/verify.sh" i.e.

  • if fail, return "1" and send email to admin
  • if success, return "0" and send email to developer.

I started reading about the command trap. Can I use it for that purpose? Is there another option?

like image 584
Chris Avatar asked Oct 06 '11 17:10

Chris


2 Answers

ssh returns the return value of the command in question, or 255 if an error occurred in ssh itself. Simply check this value and take appropriate action.

like image 75
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 16:10

Ignacio Vazquez-Abrams


You can use the $? variable to get the response code. For instance:

% ssh somebox /bin/true
% echo $?
0
% ssh somebox /bin/false
% echo $?
1
like image 8
Alfred Fazio Avatar answered Oct 17 '22 17:10

Alfred Fazio