RUNNING_APPS=$(pgrep -f "somePattern")
echo $?
#results in
1
How can I make my command pass with exit code 0?
RUNNING_APPS=$(pgrep -f "somePattern")
echo $?
#results in
1
How can I make my command pass with exit code 0?
On my Arch system, with the pgrep from procps-ng, I see this in 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.
So this is just the way it is: pgrep will exit with 1 if everything worked fine but there were no processes matching the search string. This means you will need to use a different tool. Perhaps something like Kusalananda suggested in the comments and ilkkachu posted as an answer:
running_apps=$(pgrep -f "somePattern" || exit 0)
But a better approach, IMO, would be to change your script. And instead of using set -e, have it exit manually at the important steps. Then, you can use something like this:
running_apps=$(pgrep -fc "somePattern")
if [ "$running_apps" = 0 ]; then
echo "none found"
else
echo "$running_apps running apps"
fi
With set -e, commands that on the left side of the AND (&&) or OR (||) operators don't cause the shell to exit, so you can suppress the error by adding || true.
So this should output 0 regardless of the processes found (and not exit before outputting it):
set -e
RUNNING_APPS=$(pgrep -f "somePattern" || true)
echo $?