Geekblok

B10m, BOK, Joffie - old geeks on a blog

Entries Comments



shell tips and trick, part 1

15 December, 2007 (16:21) | guides, technical | By: Joffie

Instead of another ssh guide, I thought it was about time for a first shell-scripting guide. In my daily job I often notice scripts that do work, but are not as efficient as could be. Say that I want the process id of the ssh daemon on my system. Loads of people will come up with something like:
ps -ef | grep sshd | grep -v grep | awk '{print $2}'

This does get the process id of sshd, but the above could also be written as:
ps -ef | awk '/sshd$/ {print $2}

And even this can still be written more efficient. Think about what you want to achieve. I asked for the process id of sshd. Basically the following would suffice:
cat /var/run/sshd.pid

Hey, I never really asked for a running sshd. But if I had asked for the process id of a running ssh daemon, the most simple solution would be:
ps -C sshd -o pid=

Or:
pgrep 'sshd'

Both just use one command instead of the four of the first example.

Comments

Comment from Blom
Time: December 15, 2007, 5:40 pm

Oh, I do feel your pain. Many a time do I see inefficiency in scripts at work too. And the worst part of it, is that the usual response is “if it takes too long to run, we just need bigger/better hardware” …

A common mistake I often see is MySQL queries like:

SELECT something FROM sometable WHERE field NOT LIKE ‘one’ AND field NOT LIKE ‘two’ AND field NOT LIKE ‘three’ AND [...] AND field NOT LIKE ‘twenty’;

Rewriting it to something like this makes it more readable and (in the specific case) >200% faster:

SELECT something FROM sometable WHERE field NOT IN (’one’, ‘two’, ‘three’, …, ‘twenty’);

Comment from Stefan
Time: December 19, 2007, 8:51 am

Why not: ‘pidof sshd’?

;)

Stefan

Comment from Joffie
Time: December 19, 2007, 11:28 am

You are right, pidof indeed works too. On RedHat systems (which I use most) they have put it in /sbin/, which is default not in the users path.

Nice quote from the (RedHat) man page: “pidof is simply a (symbolic) link to the killall5 program, which should also be located in /sbin.”

Write a comment





Preview: