从php运行shell脚本无法正常工作

时间:2014-05-22 21:39:22

标签: php bash

我在命令提示符下从php脚本中运行此shell脚本。

<?php
$monitorDir = 'logs';
$script = "" .
        " inotifywait -mqr --format '%w %f %e' $monitorDir | " .
        " while read dir file event;" .
        " do" .
        "   if [ \"\$event\" == \"CLOSE_WRITE,CLOSE\" ];" .
        "   then" .
        "     echo finished writing \$file; ".
        "    fi;" .
        " done";

$proc = proc_open($script, $descriptors, $pipes);

当我运行它时,我得到的输出看起来像这样:

sh: 1: [: MODIFY: unexpected operator
sh: 1: [: CLOSE_WRITE,CLOSE: unexpected operator
sh: 1: [: MODIFY: unexpected operator
sh: 1: [: OPEN: unexpected operator
sh: 1: [: MODIFY: unexpected operator

奇怪的是,当我在php中回显$script并将结果输出粘贴到命令shell时,它运行正常。

问题似乎是if [ \"\$event\" ==

任何人都能看到我在这里失踪的东西?

修改

以下是php,Appologies为格式化呈现的确切输出,但我认为我将其保留原样&#39;展示正在制作的东西。

inotifywait -mqr --format '%w %f %e' logs | while read dir file event; do if [ "$event" == "CLOSE_WRITE,CLOSE" ]; then     echo finished writing $file;   fi; done

正如我所说,当粘贴到控制台时,它运行正常,在打开proc时打开它会失败。

1 个答案:

答案 0 :(得分:1)

尝试使用escapeshellcmd转义$script,例如proc_open(escapeshellcmd($script), ...)

另外,我认为$\file应为\$file

然后:您的字符串将更具可读性 - 您将更容易发现错误 - Heredoc-syntax

$script = <<<EOD

inotifywait -mqr --format '%w %f %e' $monitorDir | 
while read dir file event;
do
  if [ "\$event" == "CLOSE_WRITE,CLOSE" ];
  then
    echo finished writing \$file
   fi;
done
EOD;
相关问题