php 执行 shell 命令转义字符

#!/usr/bin/env php
<?php
    $path = '/Users/staff/学习/z-专业(技术)';
    $target = '/Users/staff/study/technology';
  
  //重要
$path = addcslashes($path, '()');
  //
passthru("diff -rq $path $target | grep -E \"^Only in $target\" | sed -n 's/://p' | awk '{print $3\"/\"$4}' | xargs -I {} rm -r {}");
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `diff -rq /Users/staff/学习/z-专业(技术) /Users/staff/study/technology | grep -E "^Only in /Users/staff/study/technology" | sed -n 's/://p' | awk '{print $3"/"$4}' | xargs -I {} rm -r {}'

不加上面的 $path = addcslashes($path, '()'); 这行代码的时候,执行会报出上面的错误,如果把目录名字中的去掉 () ,执行就没问题,查出问题是

路径中的() 需要转义一下,转义成:'/Users/staff/学习/z-专业\(技术\)' , php里面有转义函数addcslashes,可以把字符串中的字符转义。

也可以用quotemeta函数

quotemeta ( string $string ) : string
Returns a version of str with a backslash character (\) before every character that is among these:

. \ + * ? [ ^ ] ( $ )

 

 

参考:

https://stackoverflow.com/questions/5489613/php-exec-and-spaces-in-paths

https://www.php.net/addcslashes

https://www.php.net/manual/en/function.quotemeta.php

posted on 2020-12-31 15:20  ZhYQ_note  阅读(231)  评论(0编辑  收藏  举报

导航