0

I have sh script that restart nginx like the following:

#!/bin/sh -e

set -e

error_exit() {
    d=$(date '+%D %T :: ')
    echo "$d Error: $*" >&2

    exit 1
}

if ! sudo service nginx reload
then        
    # Exit with error
    error_exit "Could not reload nginx"
fi

echo "Deployment Done!"

But my problem is that script continues execution event in case error like Reloading nginx configuration nginx [fail] and reaches Deployment Done! echo. It's seems if case is always true.

So, how could I stop executing of bash script if nginx reloading fails?

3
  • It's a sh script. – Cyrus Oct 27 '14 at 21:08
  • Yes sure, I've edited the the post – Erik Oct 28 '14 at 4:57
  • testing for > 0 would be a good idea (since 0 means success). – AD7six Oct 28 '14 at 9:49
1

Replace exit 1 by return and insert a line before fi with exit 1.

Update:

Try this with a GNU grep:

#!/bin/sh -e

set -e

error_exit() {
    d=$(date '+%D %T :: ')
    echo "$d Error: $*" >&2

    exit 1
}

out="$(sudo service nginx reload 2>&1 | grep -o fail || true)"  # new
if [ "x$out" = "xfail" ]                                        # modified
then
    # Exit with error
    error_exit "Could not reload nginx"
fi

echo "Deployment Done!"
6
  • unfortunately your magic doesn't work :( – Erik Oct 28 '14 at 4:56
  • What's the returncode (echo $?) of sudo service nginx reload if reload fails? – Cyrus Oct 28 '14 at 8:27
  • nothing because sudo service nginx reload case is always true and don't get stepped into body clause. – Erik Oct 28 '14 at 8:59
  • okay, I've updated my answer. – Cyrus Oct 28 '14 at 9:48
  • I'll try a little bit later. Is this preferable approach? Is there any best practices in checking result of such commands? – Erik Oct 28 '14 at 12:02

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.