如何测试进程是否存在于 Bash 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19284919/
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
How to test if a process exists in Bash?
提问by at.
I want to make sure node
is running when logging in. So in my .bashrc
file I have:
我想确保node
在登录时正在运行。所以在我的.bashrc
文件中我有:
pkill node
sleep 1
node server.js &
Of course, that doesn't check if node
is running... it simply kills it and starts it up again. Instead I'd like something like this:
当然,这不会检查是否node
正在运行......它只是杀死它并再次启动它。相反,我想要这样的东西:
node_process = $(pidof node)
if [not_exists node_process]; then
node server.js &
fi
The problem is the not_exists
method doesn't seem to exist :). How do I test the existence of a number or string in Bash and is this the best way to ensure node is up and running upon login?
问题是该not_exists
方法似乎不存在:)。如何在 Bash 中测试数字或字符串是否存在,这是确保节点在登录时启动并运行的最佳方法吗?
回答by chepner
You can check if a string is empty using -z
:
您可以使用以下命令检查字符串是否为空-z
:
node_process_id=$(pidof node)
if [[ -z $node_process_id ]]; then
node server.js &
fi
pidof
returns nothing if no matching processes are found, so node_process_id
would be set to an empty string.
pidof
如果找不到匹配的进程,则不返回任何内容,因此node_process_id
将设置为空字符串。