[Bash]kill指定的进程名

通过bash来kill指定的进程名,bash文件名为:/home/zcm/bin/d.sh,内容如下:

#!/bin/sh
if [ "$1" = "" ]; then
	echo "Usage: sh $0 <processname>"
	exit 0
fi
#s1=`ps -ef|grep $1|grep -v grep|awk '{print $2}'`
s1=`ps -ef|grep $1|grep -v "sh $1"`
echo "$s1"
echo "----------------------------"
echo "$s1"|while read line
do
	if [ "$line" != "" ]; then
		echo "$line"
#		echo "the pid is $line"
#		kill "$line"
	else
		echo "the pid is NULL"
	fi
done


运行结果如图:

点击看大图

 

事实上,上面的脚本没有kill掉指定的进程,只是将要kill的进程信息列了出来。我们只要加上“kill进程的pid”就可以了,完整代码如下:

#!/bin/sh
if [ "$1" = "" ]; then
	echo "Usage: sh $0 <processname>"
	exit 0
fi
s1=`ps -ef|grep $1|grep -v "sh $1"|awk '{print $2}'`
echo "$s1"|while read line
do
	if [ "$line" != "" ]; then
		echo "the pid is $line"
		kill $line
	else
		echo "the pid is NULL"
	fi
done

 

现在的运行结果是:

[zcm@bin #117]$sh b.sh bash
the pid is 2405
the pid is 2649

但是我发现:kill终端本身好像不起作用,但是当我开了几个firefox后再测试,发现所有打开的firefox进程都被kill掉了。实验证明,这个脚本是成功的!

阅读更多
个人分类: Linux_Shell
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭