Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

Eg:

#!/bin/bash
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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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"
fi

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

share|improve this answer

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

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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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