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
    You are missing a then after the if conditions – Raman Sailopal Oct 4 '17 at 11:03
  • 1
    Bash doesn't use // comments, only # – Jaroslav Kucera Oct 4 '17 at 11:09
  • 1
    Also, quotes are missing around $(...), as well as else or elif or fi. – Kusalananda Oct 4 '17 at 11:10
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.

  • Thank you Mark for the answer and link it works perfectly. – danone Oct 4 '17 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.