如何测试进程是否存在于 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:15:45  来源:igfitidea点击:

How to test if a process exists in Bash?

bashshellprocess.bash-profile

提问by at.

I want to make sure nodeis running when logging in. So in my .bashrcfile I have:

我想确保node在登录时正在运行。所以在我的.bashrc文件中我有:

pkill node
sleep 1
node server.js &

Of course, that doesn't check if nodeis 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_existsmethod 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

pidofreturns nothing if no matching processes are found, so node_process_idwould be set to an empty string.

pidof如果找不到匹配的进程,则不返回任何内容,因此node_process_id将设置为空字符串。