12

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.

4 Answers 4

16

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=$?
Sign up to request clarification or add additional context in comments.

Comments

6

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"];

Comments

4

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.

1 Comment

ahh thanks but is there any way to get the output when the php scripts are called from a bash script? That's what I meant to ask. I suppose I could rewrite the bash script in PHP to use the functionality you've described, which is useful.
0

It is more easy than the answer of Emilio:

Just execute the script

$ php -f script.php

and echo the exit code

$ echo $?

2 Comments

Seems pretty good. But if the php script says ‘echo 0’, then ‘echo $?’ prints 00. If 1, then 10.
yes, thats how echo'ing outputs to the console works in php. one can't prevent that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.