[居然没有 shellscript 节点]随手写了一个小脚本,帮助你 kill 进程。

2015-07-29 18:13:02 +08:00
 bramblex

使用方式:mykill <进程名或pid>

>> mykill 10150 #参数为pid
kill 10150 /Applications/QQ.app/Contents/MacOS/QQ? [y/n]

>> mykill qq #参数为进程名,只match到一个结果
kill 10150 /Applications/QQ.app/Contents/MacOS/QQ? [y/n]

>> mykill sh #参数为进程名,match到多个结果
22340 brambles /bin/bash
10180 brambles -zsh
22341 brambles /bin/bash
43369 brambles -zsh
43262 brambles /bin/bash
7747 brambles -zsh
matched 6 processes!

>> mykill abc #没有match到结果
no thing matched!

=====================以下是脚本代码====================
将一下代码保存到一个文件里面,并给文件执行权限就行了。

#!/bin/bash

if [[ $1 =~ ^[0-9]+$ ]]
then
    p_l=$(ps aux | awk -v pid="$1" 'NR > 1 && $2 == pid {print  $2, $1, $11}')
else
    p_l=$(ps aux | awk -v pname="$1" 'NR > 1 && tolower($11) ~ tolower(pname) {print  $2, $1, $11}')
fi

l_n=$(echo "${p_l}" | grep -v ^\s*$ |wc -l)
l_n=$(echo ${l_n})

if [ ${l_n} == 0 ]
then
    echo "no thing matched!"
elif [ ${l_n} == 1 ]
then
    p_pid=$(echo "${p_l}"| awk '{print $1}')
    p_name=$(echo "${p_l}"| awk '{print $3}')
    read -p "kill ${p_pid} ${p_name}? [y/n]" -n 1 -r
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        kill -9 ${p_pid}
    fi
    echo

else
    echo "${p_l}"
    echo "matched ${l_n} processes!"
fi
3559 次点击
所在节点    程序员
29 条回复
bramblex
2015-07-30 09:16:19 +08:00
@mongodb 对啊,不知道为什么没有
bramblex
2015-07-30 09:20:06 +08:00
@winkidney 活捉一只基佬
bramblex
2015-07-30 09:20:50 +08:00
@cnallenzhao 没折腾过,下次试试。
acgeo
2015-07-30 11:27:56 +08:00
整这么复杂 有毛用

两句命令搞定

PROCESS_NAME为想kill的进程 pgrep后会输出PID号 然后kill 你也可以把这两句写成一句~~~

pgrep PROCESS_NAME

kill PID
bramblex
2015-07-31 02:45:40 +08:00
随手看了楼上的其他回复,已block。
acgeo
2015-07-31 10:16:41 +08:00
@bramblex zhuangbility
TerrenceSun
2015-08-03 19:37:58 +08:00
@bramblex killall没有这么不济吧,-r可以用正则式来匹配。要是要求按参数而不是命令本身进行匹配的话,那的确不如自己造的顺手。
Usage: killall [-Z CONTEXT] [-u USER] [ -eIgiqrvw ] [ -SIGNAL ] NAME...
killall -l, --list
killall -V, --version

-e,--exact require exact match for very long names
-I,--ignore-case case insensitive process name match
-g,--process-group kill process group instead of process
-i,--interactive ask for confirmation before killing
-l,--list list all known signal names
-q,--quiet don't print complaints
-r,--regexp interpret NAME as an extended regular expression
-s,--signal SIGNAL send this signal instead of SIGTERM
-u,--user USER kill only process(es) running as USER
-v,--verbose report if the signal was successfully sent
-V,--version display version information
-w,--wait wait for processes to die
-Z,--context REGEXP kill only process(es) having context
(must precede other arguments)
breeswish
2015-10-16 18:17:48 +08:00
要是进程名是数字怎么办 OwO
bramblex
2015-10-16 18:23:08 +08:00
@breeswish 那就无解了 /w\

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/209343

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX