I'm trying to detect whether the zoom program is running. I also need sudo privileges in my bash script to install it with dpkg.
If I use pgrep -f "zoom" >/dev/null 2>&1
, the return code echo $?
will be correctly set to 0 if zoom is running and to 1 if not found.
By using sudo
, pgrep
picked up two additional processes: the sudo pgrep etc.
one and the pgrep etc.
child process of the sudo
one. This didn't work so I had to use a 'hacky workaround': sudo pgrep -f "[z]oom" >/dev/null 2>&1
did the trick: the regex made sure pgrep
processes aren't added to the results.
So now with sudo pgrep -f "[z]oom" >/dev/null 2>&1 ;
I have echo $?
set to 1 if the process is not running and 0 if it's running. Perfect.
But when I added this in my bash script (which I run with sudo
):
if pgrep -f "[z]oom" 2>&1 ; then
echo $?
echo "zoom is running"
This no longer works and it always says that the zoom process is running (so it always returns 0 even if zoom is not running).
Why is that?
-f
flag inpgrep
since there could be many unexpected consequences. For instance, if someone else is runninggrep zoom
at the same time, pgrep will also catch it. You should use the exact name of the process instead. If you're not sure because the process name is different then the command name, you can run first:ps -o comm -p $(pgrep -f zoom)
to find the process name, and then pgrep for it without-f
.