-1

I'm trying to kill a background process 'sleep 600'. For that I got the following script which is working fine.

ps -ef | grep "sleep 600" | grep -v grep | awk '{print $2}' | xargs -I{} kill {}

I would like to know what does 'grep -v grep' do?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Alna
  • 65
  • 7
  • 1
    `grep -v pattern` removes all lines that match the pattern. `grep -v grep` removes the `grep "sleep 600"` from the ps output. – William Pursell Jan 15 '20 at 06:54
  • 2
    Note that this particular pipeline is usually considered bad practice, as there are much better ways to do this task. (`pgrep`, `pkill`, using patterns like `grep '[s]leep'`, etc.) – William Pursell Jan 15 '20 at 06:55

2 Answers2

2

Could you please go through following.

ps -ef |                   ##Running ps -ef command to get all running pids information on server, passing its Output to next command as an Input.
grep "sleep 600" |         ##Looking for lines which have sleep 600 in it and sending its output as input to next line.
grep -v grep |             ##grep -v basically omits lines which have string grep in them, since grep command also creates a process to get string in above command so basically it is there to avoid that command's pid.
awk '{print $2}' |         ##Getting 2nd field of the process and sending it to next command as an Input.
xargs -I{} kill {}         ##Killing pid which was passed from previous command to this one.

From man grep:

-v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)

Suggestion for OP's command improvement: You could remove multiple usage of grep and awk and could do this in a single awk like:

ps -ef | awk '/sleep 600/ && !/awk/{print $2}' | xargs -I{} kill {}

OR make use of pkill option: Please make sure you test it before running in PROD/LIVE environments. Also while providing patterns make sure you are giving correct pattern which catches right process else it may kill other PIDs too, so just a fair warning here.

pkill -f 'sleep 60'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

Your command can be divided into several parts.

  1. ps -ef | grep "sleep 600"

This will try to find sleep in running process list. But the problem is, grep will catch the grep itself.

# ps -ef | grep "sleep 600"
fahad     2327 13054  0 12:52 pts/9    00:00:00 sleep 600
root      2463 21217  0 12:52 pts/14   00:00:00 grep --color=auto sleep 600

We do not need "grep --color=auto sleep 600" as it was just that command itself. So to exclude that, we can use grep -v

grep -v: "-v, --invert-match        select non-matching lines"

So, after grep -v with a word or something will exclude that match. So here you are just picking the real sleep 600 process.

Read more for grep from:

grep --help

Thank you.

Fahad Ahammed
  • 371
  • 1
  • 11
  • 23