Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a init script which is poorly designed because it does not conform to the Linux Standard Base Specifications

The following should have an exit code of 0 if running, and 3 if not running

service foo status; echo $? 

However because of the way the script is designed, it always returns a 0. I can not fix the script without a significant rewrite (because service foo restart is dependent on service foo status).

How could you work around the issue so that service foo status returns a 0 if running, and a 3 if not running?

What I have so far:

root@foo:/vagrant# service foo start
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l
1
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $?
0 # <looks good so far

root@foo:/vagrant# service foo stop
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l
0
root@foo:/vagrant# /etc/init.d/foo status | /bin/grep "up and running"|wc -l;echo $?
0 # <I need this to be a 3, not a 0
share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

You are piping the grep output to wc and echo $? would return the exit code for wc and not grep.

You could easily circumvent the problem by using the -q option for grep:

/etc/init.d/foo status | /bin/grep -q "up and running"; echo $?

If the desired string is not found, grep would return with a non-zero exit code.

EDIT: As suggested by mr.spuratic, you could say:

/etc/init.d/foo status | /bin/grep -q "up and running" || (exit 3); echo $?

in order to return with an exit code of 3 if the string is not found.

man grep would tell:

   -q, --quiet, --silent
          Quiet;  do  not  write  anything  to  standard   output.    Exit
          immediately  with  zero status if any match is found, even if an
          error was detected.  Also see the -s  or  --no-messages  option.
          (-q is specified by POSIX.)
share|improve this answer
    
To complete the answer: ... | grep -q && (exit 0) || (exit 3) . This sets the exit code as required. –  mr.spuratic Oct 14 '13 at 10:02
    
@mr.spuratic Nice. Didn't think about that. However, && (exit 0) is redundant since a match would imply that grep returns with an exit code of 0. –  devnull Oct 14 '13 at 10:07
add comment

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.