Written by James McDonald

September 11, 2011

This will seem really simple to those that know about these things, but hey I’m easily amused.

Here is a snippet from an /etc/init.d script

HTTPD=/httpd/bin/httpd
PIDFILE=/httpd/logs/httpd.pid
if pidof $HTTPD | tr ' ' '\n' | grep -w $(cat $PIDFILE); then
	return 0
fi

What I’m interested in is the pidof (Process ID of) command and the way that you chain common linux utilities to get a result

Get a list of the PID’s of the httpd binary

$ pidof httpd
15600 5702 5696

They present as a flat list so use tr to translate the spaces into newlines. Which is similar to an excel paste with transpose.

$ pidof httpd | tr ' ' '\n'
15600
5702
5696

Finally use grep to find the pid of the parent process as stored in the PID file.
The -w switch in grep is very cool it says find whole words so you won’t match watch you are looking for on a substring (e.g. ‘123’ will only match ‘123’ it won’t match ‘1234’)

$ pidof httpd | tr ' ' '\n' | grep -w $(cat /httpd/logs/httpd.pid)
5696

Interestingly with tr you can go from a newline separated (stacked) list to a space separated (flat) list


# if a file named stacked contains
1
2
3
4

# then you can turn it back into a flat list using tr
$ cat stacked | tr '\n' ' '
1 2 3 4

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…