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?
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?
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'
Your command can be divided into several parts.
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.