Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 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"

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:

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.

share|improve this answer

Your Answer


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.