【问题标题】:execute shell script code depends upon php return value执行shell脚本代码取决于php返回值
【发布时间】:2016-10-25 13:29:34
【问题描述】:

我对 PHP 了解不多,我需要运行一个依赖于 PHP 返回值的脚本。

脚本

presentDir=`pwd`
success=$(php -f $presentDir/optimize.php $file)
echo echo "value:".$success

PHP 代码

<?php
try{        
    //code  
} catch(Exception $e){
    return 1
}
return 0

执行上述shell脚本时,成功为空。

【问题讨论】:

    标签: php bash shell


    【解决方案1】:

    PHP 的 return 语句不会向 STDOUT 发送任何输出,这正是您使用 $() 构造所捕获的。要查看命令的退出值,请在 PHP 中使用 the exit statementshell's $? variable。也许这就是你要找的?

    <?php
    try {
        //code
    } catch(Exception $e){
        exit(1);
    }
    exit(0);
    ?>
    

    接着是:

    #!/bin/sh
    php -f optimize.php "$file"
    printf "PHP script returned %d" $?
    
    # or you could just use if:
    if php -f optimize.php "$file"; then
        do_stuff
    fi
    

    无需在脚本调用中包含当前工作目录。 (此外,您可以使脚本可执行并直接调用它!)

    【讨论】:

    • 我必须在退出语句后添加方括号,现在它可以正常工作了。我根据此修复编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2011-07-12
    • 2017-04-08
    • 2019-12-29
    • 2013-06-13
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多