从shell脚本中的php脚本中检索退出状态

时间:2013-09-06 00:04:26

标签: php bash shell exit-code

我有一个bash shell脚本,可以像这样调用几个PHP脚本。

#!/bin/bash

php -f somescript.php

php -f anotherscript.php

我想根据这些脚本的结果撰写错误日志和/或活动报告。

有什么方法可以在shell脚本中获取php脚本的退出状态吗?

我可以使用整数退出状态或字符串消息。

4 个答案:

答案 0 :(得分:13)

您可以使用反引号运算符轻松捕获输出,并使用 $?获取最后一个命令的退出代码:< / p>

#!/bin/bash
output=`php -f somescript.php`
exitcode=$?

anotheroutput=`php -f anotherscript.php`
anotherexitcode=$?

答案 1 :(得分:4)

Emilio的答案很好,但我想我可以为其他人扩展一点。如果你愿意,你可以在cron中使用这样的脚本,如果有错误的话就给你发电子邮件.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

使用php-cgi作为命令(而不是php)可以更容易地将url参数传递给php脚本,这些可以使用通常的PHP代码访问,例如:

$id = $_GET["myUrlParam"];

答案 2 :(得分:3)

exec命令的$output参数可用于获取另一个PHP程序的输出:

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));

运行caller.php将输出以下内容:

Array
(
    [0] => Array
        (
            [0] => my return string
            [1] => another return value
        )

    [1] => 20
)

请注意exit状态必须是0到254之间的数字。有关退货状态代码的详情,请参阅exit

答案 3 :(得分:0)

这比 Emilio 的答案更容易:

直接执行脚本

$ php -f script.php

并回显退出代码

$ echo $?
相关问题