macos 杀死进程的shell脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8343989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell script to kill a process
提问by Ana
I need to implement a shell script that kills a process. The problem is that I need to do a conditional to be able to see if the process is running or not.
我需要实现一个杀死进程的 shell 脚本。问题是我需要做一个条件才能查看进程是否正在运行。
This is my code, but it is not working:
这是我的代码,但它不起作用:
#!/bin/sh
if [ -x "MY_PROCCESS_NAME"]; then
killall MY_PROCCESS_NAME
else
echo "Doesn't exist"
fi
This is the error:
这是错误:
line 3: [: missing `]'
采纳答案by Petesh
to check if a process is running on mac os x you can use:
要检查进程是否在 mac os x 上运行,您可以使用:
pid=$(ps -fe | grep 'process name' | grep -v grep | awk '{print }')
if you want to reduce the number of shell scripts you can enclose one of the characters of the name of the process in square brackets:
如果要减少 shell 脚本的数量,可以将进程名称的字符之一括在方括号中:
pid=$(ps -fe | grep '[p]rocess name' | awk '{print }')
combined in your test this would look like:
在您的测试中结合起来,这看起来像:
pid=$(ps -fe | grep '[p]rocess name' | awk '{print }')
if [[ -n $pid ]]; then
kill $pid
else
echo "Does not exist"
fi
it's a little more complicated than you would need to do under linux as you generally have the 'pgrep' command, which is the rough equivalent of the 'ps -fe | grep ... | grep -v grep'
它比在 linux 下需要做的要复杂一些,因为您通常使用“pgrep”命令,它大致相当于“ps -fe | grep ... | grep -v grep'
回答by matchew
not sure if it would work in OSX, it works in ubuntu.
不确定它是否适用于 OSX,它适用于 ubuntu。
but as a one liner:
但作为一个班轮:
ps aux | awk '$11~/vim/ {PID = $2} END {if (PID) print "kill -9 "PID; else print "echo no process"}' | bash
ps aux | awk '$11~/vim/ {PID = $2} END {if (PID) print "kill -9 "PID; else print "echo no process"}' | bash
what it does is it finds a process, in this case, vim and returns the kill -9 pid
if no string is found it returns echo no process
it then pipes the output to bash.
它的作用是找到一个进程,在这种情况下,vim 并返回kill -9 pid
如果没有找到字符串则返回echo no process
它然后将输出通过管道传输到 bash。