2

I am trying to get a list of the running services. I ran

service --status-all

It will return something like

 [ + ]  acpid
 [ ? ]  alsa-utils
 [ + ]  apache2
 [ + ]  atd
 [ + ]  avahi-daemon
 [ ? ]  binfmt-support
 [ + ]  bluetooth
 [ - ]  bootlogd
 [ - ]  bootlogs

I try to grep and it tries to work with the special characters.

sudo service --status-all | grep '+'

Is there anything that i can do to get it to work correctly.

1
  • try with sudo service --status-all | grep -L '+' because the ' already says that it won't be escape character...
    – poz2k4444
    Jan 17, 2013 at 2:02

1 Answer 1

7

I try to grep and it tries to work with the special characters.

With basic regular expressions (BRE) enabled (the default in absence of the switches -E, -F or -P), grep interprets the plus character as a literal +.

The problem is that only lines that begin with [ + ] or [ - ] get sent to STDOUT, while lines that begin with [ ? ] get sent to STDERR. Only STDOUT gets piped to grep; STDERR gets printed directly on the terminal.

To obtain the output you're expecting, execute the following command:

service --status-all 2>&1 | grep '+'

2>&1 sends STDERR to STDOUT, so grep is able to filter it.

Since you're printing only lines begnning with  [ + ]  , you might as well filter that part out. To do so, you can use the -o switch to print only matched output, the -P switch to enable Perl Compatible Regular Expressions (PCRE) and a look-behind assertion ((?<=...)):

service --status-all 2>&1 | grep -Po '(?<= \[\ \+ \]  ).*'

Note that with PCRE, you have to escape the plus sign and the brackets with a backslash.

The same result can be achieved with BRE, without look-behinds and without knowing the exact number of spaces if you use sed:

service --status-all 2>&1 | grep '+' | sed 's/.*] *//'

Here, the BRE .*] * (everything up to the right bracket, followed by any number of spaces) gets replaced by the empty string.

2
  • thanks great answer is there any way to remove the [ + ]
    – WojonsTech
    Jan 17, 2013 at 2:22
  • 1
    @WojonsTech: I've updated my answer.
    – Dennis
    Jan 17, 2013 at 2:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .