RUNNING_APPS=$(pgrep -f "somePattern")
echo $?
#results in
1如何使用退出代码0使命令通过?
发布于 2020-08-11 13:41:20
在我的拱形系统中,使用来自pgrep的procps-ng,我在man pgrep中看到了这一点:
EXIT STATUS
0 One or more processes matched the criteria. For
pkill the process must also have been success‐
fully signalled.
1 No processes matched or none of them could be
signalled.
2 Syntax error in the command line.
3 Fatal error: out of memory etc.所以这就是它的方式:如果一切正常,pgrep将退出1,但是没有匹配搜索字符串的进程。这意味着您需要使用不同的工具。也许类似于Kusalananda在评论和伊尔卡丘中所建议的东西:
running_apps=$(pgrep -f "somePattern" || exit 0)但更好的办法,国际海事组织,将是改变你的脚本。而不是使用set -e,让它在重要的步骤手动退出。然后,您可以使用这样的东西:
running_apps=$(pgrep -fc "somePattern")
if [ "$running_apps" = 0 ]; then
echo "none found"
else
echo "$running_apps running apps"
fi发布于 2020-08-11 14:36:33
使用set -e,在AND (&&)或or (||)运算符左侧的命令不会导致shell退出,因此可以通过添加|| true来抑制错误。
因此,这应该输出0,而不管所找到的进程是什么(而不是在输出之前退出):
set -e
RUNNING_APPS=$(pgrep -f "somePattern" || true)
echo $?https://unix.stackexchange.com/questions/603982
复制相似问题