9

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?

1
  • I've been pulling my hair out for an hour because of this pgrep issue. It felt like someone was playing with me. Unbelievable. 😓 But now I understand that it's because the script I'm trying to run is named after the executable I'm trying to match with pgrep 🤡 Commented Aug 11 at 22:04

2 Answers 2

7

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. :) 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$' Commented Nov 30, 2022 at 3:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.