0

Hi I am trying to make a script which checks 3 files before run. If they are running or not. What is wrong with my code?

#!/bin/bash
if [[ ! $(pgrep -f a1.php) ]];  //check if any pid number returned if yes close and exit this shell script    
    exit 1
if [[ ! $(pgrep -f a2.php) ]];  //check if any pid number returned if yes close and exit this shell script 
    exit 1
if [[ ! $(pgrep -f a3.txt) ]];  //check if any pid number returned if yes close and exit this shell script  
    exit 1
else
    php -f a.php; php -f b.php; sh -e a3.txt   //3 files is not running now we run these process one by one
fi
3
  • 3
    You are missing a then after the if conditions Commented Oct 4, 2017 at 11:03
  • 1
    Bash doesn't use // comments, only # Commented Oct 4, 2017 at 11:09
  • 1
    Also, quotes are missing around $(...), as well as else or elif or fi.
    – Kusalananda
    Commented Oct 4, 2017 at 11:10

1 Answer 1

1
  1. You are not using the right format for if in bash, in particular you have missed out then and fi.

  2. $() subshell is possibly not doing what you think. It returns the stdout of the command inside, not the exit code (which is normally what you test against). Either $(pgrep -c -f a1.php) -gt 0 using the -c flag to return the number of matching processes, or pgrep -f a1.php > /dev/null using the exit code would be better.

    [[ ! $(pgrep -f a1.php) ]] might work in this case, but [[ $(pgrep -f a1.php) ]] would fail if more than one process matched, so it is fragile.

Try,

if [[ $(pgrep -c -f a1.php) -gt 0 ]]; then
    exit 1
fi
if [[ $(pgrep -c -f a2.php) -gt 0 ]]; then
    exit 1
fi
if [[ $(pgrep -c -f a3.txt) -gt 0 ]]; then
    exit 1
fi

php -f a.php; php -f b.php; sh -e a3.txt

OR ALTERNATIVELY

pgrep -f a1.php > /dev/null && exit 1
pgrep -f a2.php > /dev/null && exit 1
pgrep -f a3.php > /dev/null && exit 1

php -f a.php; php -f b.php; sh -e a3.txt

See http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html for more information on the if statement.

1
  • Thank you Mark for the answer and link it works perfectly.
    – danone
    Commented Oct 4, 2017 at 11:29

You must log in to answer this question.

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