Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pgrep command in an if statement

Tags:

linux

bash

sh

I need to have a .sh file that will echo 0 if my python service is not running. I know that pgrep is the command I want to use, but I am getting errors using it.

if [ [ ! $(pgrep -f service.py) ] ]; then
    echo 0
fi

Is what I found online, and I keep getting the error

./test_if_running.sh: line 3: syntax error near unexpected token `fi'
./test_if_running.sh: line 3: `fi;'

When I type

./test_if_running.sh
like image 616
BaleineBleue Avatar asked Feb 05 '26 09:02

BaleineBleue


1 Answers

The issue in your code is the nested [ ... ]. Also, as @agc has noted, what we need to check here is the exit code of pgrep and not its output. So, the right way to write the if is:

if ! pgrep -f service.py &> /dev/null 2>&1; then
  # service.py is not running
fi
like image 88
codeforester Avatar answered Feb 07 '26 22:02

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!