I want to build a small script (called check_process.sh
) that checks if a certain process $PROC_NAME
is running. If it does, it returns its PID or -1 otherwise.
My idea is to use pgrep -f <STRING>
in a command substitution.
If I run this code directly in the command line:
export ARG1=foo_name
export RES=$(pgrep -f ${ARG1})
if [[ $RES == "" ]]; then echo "-1" ; else echo "$RES"; fi
everything goes fine: PID
or -1 depending on the process status.
My script check_process.sh
contains the same lines plus an extra variable to pass the process' name :
#!/bin/bash
export ARG1=$1
export RES=$(pgrep -f ${ARG1})
if [[ $RES == "" ]]; then echo "-1" ; else echo "$RES"; fi
But this code does not work!
If the process is currently running I get two PID
s (the process' PID and something else...), whereas when I check a process that is not running I get the something else !
I am puzzled. Any idea? Thanks in advance!