Wednesday, August 18, 2010

UNIX - handle Kill when no PID


I was grepping for a particular process say 'Sync' in my process listing

$ ps -ef | grep Sync
testuser 26057 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 10
testuser 26066 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 14
testuser 26067 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 22
testuser 26266 23299 0 06:21 pts/3 00:00:00 grep Sync

The 'grep' from the above listing can be removed by using a regular expression:

$ ps -ef | grep [S]ync
testuser 26057 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 10
testuser 26066 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 14
testuser 26067 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 22

I wrote a one liner which basically extracts the PIDs from the above output and then kill them.

$ kill -9 $(ps -ef | awk '/[S]ync/ {print $2}')

ps -ef | grep [S]ync
is same as
ps -ef | awk '/[S]ync/'

Now if there is no 'Sync' process running , the above command is going to throw a message like this:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

To handle this, here is the solution:

$ ps -ef | awk '/[S]ync/ {print $2}' | xargs -r kill -9

From XARGS(1) man page:

--no-run-if-empty, -r
If the standard input does not contain any nonblanks, do not run the command.
Normally, the command is run once even if there is no input. This option is a GNU extension.

Sunday, August 15, 2010

UNIX - Print first and last line of file - sed, awk

Input file:

$ cat file.txt
50
57
52
60
52
90

Required output: Print the first and the last line of the above file.

50
90

Few alternatives using bash, sed and awk :

$ head -1 file.txt; tail -1 file.txt

$ sed -n '1p;$p' file.txt

$ awk 'NR==1; END{print}' file.txt

And a simple python program to achieve the same:

$ cat print-first-last-line.py
fp = open('file.txt','r')
data = fp.readlines()
fp.close()
print data[0],
print data[len(data)-1],

Related:

- Print next few lines after pattern is found using awk

© Jadu Saikia http://unstableme.blogspot.com