PHP exec with JQ - [] brackets error: PHP Fatal error: Cannot use [] for reading

PHP exec with JQ - [] brackets error: PHP Fatal error: Cannot use [] for reading

我在 PHP 脚本中有以下命令:

shell_exec('cd /home/scripts/scripts; ./total.sh | jq '.hits .hits [] .fields["termListData.terms"] | .[]' | wc -l > /home/data/total.csv');

这给了我:PHP 致命错误:无法使用 [] 读取 ...

仅来自命令行的命令就可以完美运行,但在 php 脚本中时就不行了。我做错了什么?

问题是您的命令执行中有单引号

你可以将你的命令一分为二

$jq_args = '.hits .hits [] .fields["termListData.terms"] | .[]';
$cmd = 'cd /home/scripts/scripts; ./total.sh | jq '.escapeshellarg($jq_args).' | wc -l > /home/data/total.csv';
shell_exec($cmd);