Search code examples
shellgrepps

Shell Script : Grep usage


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?


Solution

  • 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'