php shell_exec 中的下划线

Underscore in php shell_exec

我尝试在 php shell_exec 中执行 grep 命令。它工作正常,除了当我在搜索词中有下划线时它会失败。我似乎无法弄清楚为什么会因为下划线而失败,因为搜索词中带有下划线的 grep 命令在下面的 shell 代码中有效:

$output = shell_exec("grep -l -r '$search_word'"); 

search_word 变量中的内容是数据库中的动态内容,但给我带来麻烦的词是 base_64

在 PHP 生成子进程之前,您的命令将被 $search_word 评估:

grep -l -r '....'
# So in $search_word is set to `john doe` it will become:
grep -l -r 'john doe'

PHP 的行为方式我不确定,它可能在等待进程完成时停止,它可能已经关闭了标准输入。

您的上述命令需要来自标准输入的输入,因为没有指定文件名,细分:

grep [option]... [pattern] [file]...
-l will only print file name of the matched file
-r recursive search.

TLDR:你想指定一个文件/目录来搜索:

$output = shell_exec("grep -l -r '$search_word' ."); 
// Or maybe
$output = shell_exec("grep -l -r '${search}_word' ."); # will use $search variable as an input from PHP while _word is a string now.

试试这样: $output = shell_exec("grep -l -r '$search_word' ./*");