I have a server in which there are about a 100 Cron jobs that run various PHP scripts. The task at hand is to generate an alert any time an error occurs in the execution of a PHP script.

The Crons are set as follows:

30 08 * * * /usr/bin/php /var/www/html/phpscirpt1.php > /var/www/html/phpscript1.log 2>&1

What I have tried is placing an && in the end but this generates the Alert Email either way

30 08 * * * /usr/bin/php /var/www/html/phpscript1.php > /var/www/html/phpscript1.log 2>&1 && <Generate Mail>

The ideal case that should work would be

 /bin/bash /home/myUser/testfile.sh > /home/myUser/testfile.log 2>&1 ; [$? == 1] && /bin/bash script.sh

The following is just a sample for testing purposes, when

/bin/bash /home/myUser/testfile.sh > /home/myUser/testfile.log 2>&1

is executed testfile.sh only creates a directory. When the above command is executed the first time echo $? gives the output 0, but running the command again return 1, because the scripts returns and logs an error

mkdir: cannot create directory `/home/myUser/testdir': File exists

And Basically this is what is required that is whenever the script in a cron fails it should generate an Alert in the form of an Email. In the above example script.sh contains a mail -s command to send the Email.

But when the complete command is executed an error is returned which is as follows

/bin/bash /home/myUser/testfile.sh > /home/myUser/testfile.log 2>&1 ; [$? == 1] && /bin/bash script.sh
-bash: [1: command not found

I would greatly appreciate any guidance that could be provided in resolving this error. Thank you


Basically your solution is good. You have just made simple bash syntax error. You have to put spaces around '[' and ']' characters:

[ $? == 1 ]

I've tested it on my box and it works. I would also suggest to test error code as not equal 0 ([ $? -ne 0 ]), unless you are sure that you want to react only on error code 1.

  • 1
    BTW "==" may not work everywhere. Better use "=" or "-eq". – rudimeier Sep 15 '16 at 7:27
  • Thank you this worked. Very much appreciated. And thanks for the recommendations as well. I will surely follow through. – Mustafa Mujahid Sep 15 '16 at 8:54

Any of the following should work:

30 08 * * * /usr/bin/php /var/www/html/phpscript1.php > /var/www/html/phpscript1.log 2>&1 || <Generate Mail>
30 08 * * * /usr/bin/php /var/www/html/phpscript1.php > /var/www/html/phpscript1.log 2>&1 ; [ $? -ne 0 ] && <Generate Mail>

The first uses a logical OR || instead of logical AND && which is based off of the return value from your script (0 is success anything else is failure).

The second needed a space between the [ and the $? to work properly.

  • Thank you for you suggestion this worked. Much appreciated. – Mustafa Mujahid Sep 15 '16 at 8:55

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.