I just want to return true or false if a service is running. Here is where I'm at, not first try or last but current at writing:

service iptables status | grep -qi "not running"

The sdtout for service iptables status when it's stopped is iptables: Firewall is not running When I run what I came up with is nothing on a new line, which I guess is not unexpected as 0 is true and non-0 is false. So, I need to test to ensure it works, but I'm unsure what to do. Here is the try:

service iptables status | grep -qi "not running" || echo "stopped"

so when the service is stopped I expected to see stopped but I didn't get anything but a new line.

service iptables status | grep -qi "not running" && echo "stopped"

You just need to replace || with &&. One confusing thing about shell scripting is that 0 is true and any other number is false, opposite to most other languages. This is just because programs generally return a 0 for success.

I also need to add an 2>&1 after status as service on my distro outputs to stderr, doesn't look like its a problem for you though.

| improve this answer | |
  • IMHO better to think of it as exit status and not boolean true / false. Thus if exit status == EXIT_SUCCESS then …. Grep also only uses 1 for non-match. Anything > 1 is error code. – Runium Jan 11 '14 at 10:07
  • 1
    Sure, but sooner or later you have to use true or false builtins for something. Although succeed and fail may be more intuitive names for them :) – Graeme Jan 11 '14 at 11:49
  • No. true and false are boolean values. My point, perhaps poorly conveyed, is that exit status is not a boolean value. It evaluates to true and false, but the value falls between 0 and 255. We also have ((1)) and ((0)). – Runium Jan 12 '14 at 1:55

If grep does not see a match, it will return a non-zero code. A return of 0 means that a match was found. You probably want:

service iptables status | grep -qi 'not running' && echo 'Stopped'
| improve 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.