8

I'm running a GUI program called zeal(compiled from src) and add a script(zeal.sh) for the executable:

#!/bin/bash

if pgrep zeal &>/dev/null; then
    printf "already on\n"
else
    ~/tools/zeal/zeal/zeal &>/dev/null &
fi

The strange thing is that when I run this script like /path/to/zeal.sh, it always tells "already on", while with bash /path/to/zeal.sh it correctly decides whether the process is running or not.

I also checked other GUI programs(like firefox) with similar scripts and they work fine.

So how can this happen and how to fix it?

2 Answers 2

6

The long option --exact proposed in Hauke's answer didn't work on some systems. You can use the equivalent short option -x instead.

#!/bin/bash

if pgrep -x "zeal" > /dev/null
then
    echo "Running"
else
    echo "Stopped"
fi
1
  • And if you get the error 'pgrep unary operator expected', make sure to leave the square brackets off of the 'if' statement. Common rookie mistake. :)
    – K.S.
    Commented Jun 12, 2017 at 17:36
3

The problem is that the direct call makes the script name the command name, see

cat /proc/$PID/comm

That causes pgrep to match. If called via bash then the command name is "bash".

Use

pgrep --exact zeal

instead.

1
  • The --exact flag does not work on macOS but you can use a regex pattern like this: [$]> pgrep '^zeal$'
    – Andy
    Commented Nov 30, 2022 at 3:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .