
RUNNING_APPS=$(pgrep -f "somePattern")
echo $?
#results in
1
如何使我的命令通過退出代碼 0?
答案1
在我的 Arch 系統上,透過pgrep
from 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 在評論中建議的那樣ilkkachu 作為答案發布:
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
答案2
對於AND ( ) 或 OR ( ) 運算set -e
子左側的 , 命令不會導致 shell 退出,因此您可以透過新增 來抑制錯誤。&&
||
|| true
因此,0
無論找到哪個進程,都應該輸出(並且在輸出之前不退出):
set -e
RUNNING_APPS=$(pgrep -f "somePattern" || true)
echo $?