首页 > 解决方案 > php 使用 at 命令执行 bash 脚本

问题描述

您好,我正在尝试在我的 php 脚本中执行 shell 命令,但它不起作用。我的 php 脚本:

           //I save the Order 
            $holdedOrder->save();
            $id = $holdedOrder->id;
            $old_path = getcwd();
            chdir(__DIR__.'/../');
            $scriptFile = 'anacron_job_unhold_order.sh';
            $bool = file_exists($scriptFile);
            //$bool is true !

            //this command works in shell but not in here do not know why
            $s = shell_exec("echo \"/usr/bin/bash $scriptFile $id\" | /usr/bin/at now +$when");
            chdir($old_path);
            return [$s,$bool];

$when 具有有效值4 hours4 days...命令将是:

echo bash anacron_job_unhold_order.sh 29 | at now +1 minutes

输出为空。尝试exec()返回 127 代码

编辑:我从 /etc/at.deny 中删除了 www-data 仍然是同样的问题

标签: phpshellyii2scheduled-tasks

解决方案


该命令shell_exec("echo \"/usr/bin/bash $scriptFile $id\" | /usr/bin/at now +$when");可能是导致问题的原因,您应该仔细查看其工作原理at

该命令应该类似于

at [options] [job...]

at要从命令而不是 STDIN分配作业,请使用heredoc syntax

at now + 1 minute <<< 'touch /tmp/test'

所以 PHP 代码应该是这样的;

$s = shell_exec("/usr/bin/at now + {$when} <<< '/usr/bin/bash {$scriptFile} {$id}'");
exec($s, $output, $return_var);

推荐阅读