doucao1066 2014-05-22 21:39
浏览 27

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

I'm running this shell script from within a php script at the command prompt.

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

When I run it I end up with output that looks like this:

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

The strange thing is, when I echo out $script in the php and paste the resulting output in to the command shell it runs fine.

It looks like the problem is around if [ \"\$event\" ==.

Anyone see what I'm missing here?

Edit

Below is the exact output rendered by the php, Appologies for the formatting but I thought I'd leave it 'as is' to demonstrate what is being produced.

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

As I say, when pasted in to the console it runs fine, it just fails when opened with proc open.

  • 写回答

1条回答 默认 最新

  • drydaenth257216154 2014-05-22 22:09
    关注

    Try escaping your $script with escapeshellcmd, e.g. proc_open(escapeshellcmd($script), ...).

    Also, I think $\file should be \$file.

    And then: your string will be much more readable - and you will spot errors easier - with 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;
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制