1

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?

3
  • 4
    Does the name of the script include the word 'zoom'?
    – Haxiel
    Nov 24, 2021 at 16:39
  • I cannot replicate this behaviour, unless when, like @Haxiel suggest, use the search term in the name of the script.
    – db-inf
    Nov 24, 2021 at 16:41
  • You should avoid using the -f flag in pgrep since there could be many unexpected consequences. For instance, if someone else is running grep 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.
    – aviro
    Nov 24, 2021 at 17:11

1 Answer 1

1

The problem is the -f. Just use

pgrep -x zoom >/dev/null 2>&1
1
  • You assume that the process name is exactly "zoom", which might not be the case. That's why I suggested in another comment to run ps -o comm -p $(pgrep -f zoom) first to find the exact process name, and then he can use it with -x.
    – aviro
    Nov 24, 2021 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.