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.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command. $ echo $?
To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command. The command was successful.
To display the exit code for the last command you ran on the command line, use the following command: $ echo $?
The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range.
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="[email protected]"
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With