I'm writing a deployment script, and I need to rollback if any errors occurred.


ssh myapp '
    mkdir /some/dir
    # check if above command failed, and execute rollback script if needed
# or maybe do it from here?

Right now when I execute this script, if mkdir fails, it prints it on my screen and continues execution. I need to catch that error and do something about it.


The exit status of ssh will be the exit status of the remote command. For instance

ssh myapp 'exit 42'
echo $?

should print 42 ($? is the exit status of the last command executed).

One option is to exit right away if the mkdir fails:

ssh myapp 'mkdir /some/dir || exit 42; do-more-stuff'
if [[ $? = 1 ]]; then
   echo "Remote mkdir failed"

It is probably better to try to handle any remote failures in your script, if possible.


If you really need to catch the error message you can try this:

result=`ssh myapp 'mkdir /some/dir' 2>&1`
if [[ -n $result ]]; then
    echo "the following error occurred: $result"

By this you redirect the standard error output to the standard output and save the output of the ssh command to $result. If you just need the error code / exit status, see this answer.

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.