Retrieve exit status from php script inside of shell script

随声附和 提交于 2019-12-14 00:19:50

问题


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.


回答1:


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=$?



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/18647841/retrieve-exit-status-from-php-script-inside-of-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!