program story

bash와 regex를 사용하여 한 줄로 프로세스를 찾아서 죽이기

inputbox 2020. 10. 3. 10:37
반응형

bash와 regex를 사용하여 한 줄로 프로세스를 찾아서 죽이기


프로그래밍 중에 프로세스를 종료해야하는 경우가 많습니다.

지금하는 방법은 다음과 같습니다.

[~]$ ps aux | grep 'python csp_build.py'
user    5124  1.0  0.3 214588 13852 pts/4    Sl+  11:19   0:00 python csp_build.py
user    5373  0.0  0.0   8096   960 pts/6    S+   11:20   0:00 grep python csp_build.py
[~]$ kill 5124

프로세스 ID를 자동으로 추출하고 같은 줄에서 죽일 수 있습니까?

이렇게 :

[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>

에서는 bash다음을 수행 할 수 있어야합니다.

kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')

그 작동에 대한 세부 사항은 다음과 같습니다.

  • ps당신에게 모든 프로세스의 목록을 제공합니다.
  • grep검색 문자열을 기반으로 하는 필터 [p]는 실제 grep프로세스 자체 를 선택하지 못하게하는 트릭 입니다.
  • awk당신에게 PID 각 라인의 두 번째 필드를 제공합니다.
  • $(x)구조체 수단 실행할 x다음 출력을 받아 그 명령 행 입었다. ps위의 구성 내부 에있는 해당 파이프 라인 의 출력은 프로세스 ID 목록이므로 kill 1234 1122 7654.

다음은 실제 상황을 보여주는 기록입니다.

pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+  Terminated              sleep 3600
[1]   Terminated              sleep 3600
[2]   Terminated              sleep 3600
[3]-  Terminated              sleep 3600
[4]+  Terminated              sleep 3600

그리고 당신은 그것이 모든 침목을 끝내는 것을 볼 수 있습니다.


설명 grep '[p]ython csp_build.py'조금 더 세부 비트를 :

당신은 않을 경우 sleep 3600 &다음 ps -ef | grep sleep, 당신이 얻을하는 경향 이 개 와 프로세스 sleep그것에을의 sleep 3600grep sleep(그들은 둘 다 가지고 있기 때문에 sleep로켓 과학이 아니다 그, 그 (것)들에서).

그러나 ps -ef | grep '[s]leep'그 안에 프로세스를 생성하지 sleep않고 대신 생성 grep '[s]leep'하고 여기에 까다로운 부분이 있습니다. grep"문자 클래스의 모든 문자 [s]( s) 다음에 오는 문자 클래스의 모든 문자를 찾고 있기 때문에는이를 찾지 못합니다 leep.

즉,을 찾고 sleep있지만 그렙 과정은 grep '[s]leep'가지고 있지 않는 sleep그것에서.

(여기 누군가에 의해) 내가 이것을 보았을 때 나는 즉시 그것을 사용하기 시작했습니다.

  • 추가하는 것보다 프로세스가 하나 적습니다 | grep -v grep.
  • 우아 하고 은밀한 드문 조합입니다 :-)

능력이 있다면

pkill -f csp_build.py

전체 인수 목록 대신 프로세스 이름에 대해서만 grep하려면 off를 그대로 두십시오 -f.


One liner:

ps aux | grep -i csp_build | awk '{print $2}' | xargs sudo kill -9

  • Print out column 2: awk '{print $2}'
  • sudo is optional
  • Run kill -9 5124, kill -9 5373 etc (kill -15 is more graceful but slightly slower)

Bonus:

I also have 2 shortcut functions defined in my .bash_profile (~/.bash_profile is for osx, you have to see what works for your *nix machine).

  1. p keyword
    • lists out all Processes containing keyword
    • usage e.g: p csp_build , p python etc

bash_profile code:

# FIND PROCESS
function p(){
        ps aux | grep -i $1 | grep -v grep
}
  1. ka keyword
    • Kills All processes that have this keyword
    • usage e.g: ka csp_build , ka python etc
    • optional kill level e.g: ka csp_build 15, ka python 9

bash_profile code:

# KILL ALL
function ka(){

    cnt=$( p $1 | wc -l)  # total count of processes found
    klevel=${2:-15}       # kill level, defaults to 15 if argument 2 is empty

    echo -e "\nSearching for '$1' -- Found" $cnt "Running Processes .. "
    p $1

    echo -e '\nTerminating' $cnt 'processes .. '

    ps aux  |  grep -i $1 |  grep -v grep   | awk '{print $2}' | xargs sudo kill -klevel
    echo -e "Done!\n"

    echo "Running search again:"
    p "$1"
    echo -e "\n"
}

Try using

ps aux | grep 'python csp_build.py' | head -1 | cut -d " " -f 2 | xargs kill

killall -r regexp

-r, --regexp

Interpret process name pattern as an extended regular expression.


You may use only pkill '^python*' for regex process killing.

If you want to see what you gonna kill or find before killing just use pgrep -l '^python*' where -l outputs also name of the process. If you don't want to use pkill, use just:

pgrep '^python*' | xargs kill


Use pgrep - available on many platforms:

kill -9 `pgrep -f cps_build`

pgrep -f will return all PIDs with coincidence "cps_build"


you can do it with awk and backtics

ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`

$2 in awk prints column 2, and the backtics runs the statement that's printed.

But a much cleaner solution would be for the python process to store it's process id in /var/run and then you can simply read that file and kill it.


My task was kill everything matching regexp that is placed in specific directory (after selenium tests not everything got stop). This worked for me:

for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done

To kill process by keyword midori, for example:

kill -SIGTERM $(pgrep -i midori)


This will return the pid only

pgrep -f 'process_name'

So to kill any process in one line:

kill -9 $(pgrep -f 'process_name')

or, if you know the exact name of the process you can also try pidof:

kill -9 $(pidof 'process_name')

But, if you do not know the exact name of the process, pgrep would be better.

If there is multiple process running with the same name, and you want to kill the first one then:

kill -9 $(pgrep -f 'process_name' | head -1)

Also to note that, if you are worried about case sensitivity then you can add -i option just like in grep. For example:

kill -9 $(pgrep -fi chrome)

More info about signals and pgrep at man 7 signal or man signal and man pgrep


A method using only awk (and ps):

ps aux | awk '$11" "$12 == "python csp_build.py" { system("kill " $2) }'

By using string equality testing I prevent matching this process itself.


ps -o uid,pid,cmd|awk '{if($1=="username" && $3=="your command") print $2}'|xargs kill -15

Give -f to pkill

pkill -f /usr/local/bin/fritzcap.py

exact path of .py file is

# ps ax | grep fritzcap.py
 3076 pts/1    Sl     0:00 python -u /usr/local/bin/fritzcap.py -c -d -m

I started using something like this:

kill $(pgrep 'python csp_build.py')

Kill our own processes started from a common PPID is quite frequently, pkill associated to the –P flag is a winner for me. Using @ghostdog74 example :

# sleep 30 &                                                                                                      
[1] 68849
# sleep 30 &
[2] 68879
# sleep 30 &
[3] 68897
# sleep 30 &
[4] 68900
# pkill -P $$                                                                                                         
[1]   Terminated              sleep 30
[2]   Terminated              sleep 30
[3]-  Terminated              sleep 30
[4]+  Terminated              sleep 30

You don't need the user switch for ps.

kill `ps ax | grep 'python csp_build.py' | awk '{print $1}'`

In some cases, I'd like kill processes simutaneously like this way:

➜  ~  sleep 1000 &
[1] 25410
➜  ~  sleep 1000 &
[2] 25415
➜  ~  sleep 1000 &
[3] 25421
➜  ~  pidof sleep
25421 25415 25410
➜  ~  kill `pidof sleep`
[2]  - 25415 terminated  sleep 1000                                                             
[1]  - 25410 terminated  sleep 1000
[3]  + 25421 terminated  sleep 1000

But, I think it is a little bit inappropriate in your case.(May be there are running python a, python b, python x...in the background.)


I use this to kill Firefox when it's being script slammed and cpu bashing :) Replace 'Firefox' with the app you want to die. I'm on the Bash shell - OS X 10.9.3 Darwin.

kill -Hup $(ps ux | grep Firefox | awk 'NR == 1 {next} {print $2}' | uniq | sort)


I use gkill processname, where gkill is the following script:

cnt=`ps aux|grep $1| grep -v "grep" -c`
if [ "$cnt" -gt 0 ]
then
    echo "Found $cnt processes - killing them"
    ps aux|grep $1| grep -v "grep"| awk '{print $2}'| xargs kill
else
    echo "No processes found"
fi

NOTE: it will NOT kill processes that have "grep" in their command lines.


If pkill -f csp_build.py doesn't kill the process you can add -9 to send a kill signall which will not be ignored. i.e. pkill -9 -f csp_build.py


The following command will come handy:

kill $(ps -elf | grep <process_regex>| awk {'print $4'})

eg., ps -elf | grep top

    0 T ubuntu    6558  6535  0  80   0 -  4001 signal 11:32 pts/1    00:00:00 top
    0 S ubuntu    6562  6535  0  80   0 -  2939 pipe_w 11:33 pts/1    00:00:00 grep --color=auto top

kill -$(ps -elf | grep top| awk {'print $4'})

    -bash: kill: (6572) - No such process
    [1]+  Killed                  top

If the process is still stuck, use "-9" extension to hardkill, as follows:

kill -9 $(ps -elf | grep top| awk {'print $4'})

Hope that helps...!


Find and kill all the processes in one line in bash.

kill -9 $(ps -ef | grep '<exe_name>' | grep -v 'grep' | awk {'print $2'})
  • ps -ef | grep '<exe_name>' - Gives the list of running process details (uname, pid, etc ) which matches the pattern. Output list includes this grep command also which searches it. Now for killing we need to ignore this grep command process.
  • ps -ef | grep '<exec_name>' | grep -v 'grep' - Adding another grep with -v 'grep' removes the current grep process.
  • Then using awk get the process id alone.
  • Then keep this command inside $(...) and pass it to kill command, to kill all process.

You can use below command to list pid of the command. Use top or better use htop to view all process in linux. Here I want to kill a process named

ps -ef | grep '/usr/lib/something somelocation/some_process.js'  | grep -v grep | awk '{print $2}'

And verify the pid. It must be proper.To kill them use kill command.

sudo kill -9 `ps -ef | grep '/usr/lib/something somelocation/some_process.js'  | grep -v grep | awk '{print $2}'`

Eg:- is from htop process list.

sudo kill -9 `ps -ef | grep '<process>'  | grep -v grep | awk '{print $2}'`

This resolves my issues. Always be prepared to restart process if you accidentally kill a process.

참고URL : https://stackoverflow.com/questions/3510673/find-and-kill-a-process-in-one-line-using-bash-and-regex

반응형