I have a bash shell script that calls a few PHP scripts like this.
#!/bin/bash
php -f somescript.php
php -f anotherscript.php
I want to compose an error log and/or an activity report based on the results of those scripts.
Is there any way I can get the exit status of the php script in the shell script?
I could either use integer exit statuses or string messages.
You can easily catch the output using the backtick operator, and get the exit code of the last command by using $?:
#!/bin/bash
output=`php -f somescript.php`
exitcode=$?
anotheroutput=`php -f anotherscript.php`
anotherexitcode=$?
Emilio's answer was good but I thought I could extend that a bit for others. You can use a script like this in cron if you like, and have it email you if there is an error.. YAY :D
#!/bin/sh
EMAIL="myemail@foo.com"
PATH=/sbin:/usr/sbin:/usr/bin:/usr/local/bin:/bin
export PATH
output=`php-cgi -f /www/Web/myscript.php myUrlParam=1`
#echo $output
if [ "$output" = "0" ]; then
echo "Success :D"
fi
if [ "$output" = "1" ]; then
echo "Failure D:"
mailx -s "Script failed" $EMAIL <<!EOF
This is an automated message. The script failed.
Output was:
$output
!EOF
fi
Using php-cgi
as the command (instead of php
) makes it easier to pass url parameters to the php script, and these can be accessed using the usual php code eg:
$id = $_GET["myUrlParam"];
The $output
parameter of the exec
command can be used to get the output of another PHP program:
callee.php
<?php
echo "my return string\n";
echo "another return value\n";
exit(20);
caller.php
<?php
exec("php callee.php", $output, $return_var);
print_r(array($output, $return_var));
Running caller.php will output the following:
Array
(
[0] => Array
(
[0] => my return string
[1] => another return value
)
[1] => 20
)
Note the exit
status must be number in the range of 0-254. See exit
for more info on return status codes.