List running services

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.

WojonsTech

Posted 2013-01-17T01:43:02.403

Reputation: 296

try with sudo service --status-all | grep -L '+' because the ' already says that it won't be escape character... – poz2k4444 – 2013-01-17T02:02:13.653

Answers

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.

Dennis

Posted 2013-01-17T01:43:02.403

Reputation: 42 934

thanks great answer is there any way to remove the [ + ] – WojonsTech – 2013-01-17T02:22:12.227

1@WojonsTech: I've updated my answer. – Dennis – 2013-01-17T02:33:14.957