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.
