这个简单的命令如果粘贴到终端中可以正常工作,但在 php 中则不起作用。
for f in a b c d e; do echo ${f/a/p}; done; 2>&1
终端
p
b
c
d
e
PHP
$command = "for f in a b c d e; do echo \${f/a/p}; done;";
$command .= " 2>&1";
echo shell_exec($command);
什么也不输出。
$command = "for f in a b c d e; do echo \$\{f/a/p\}; done;";
$command .= " 2>&1";
echo shell_exec($command);
输出:
${f/a/p}
${f/a/p}
${f/a/p}
${f/a/p}
${f/a/p}
有什么问题吗?
谢谢
最佳答案
正如 @jhnc 提到的,问题是它使用 shell 而不是 bash。 您可以使用命令参数执行 bash,如下所示:
$command = 'for f in a b c d e; do echo ${f/a/p}; done;';
$command .= " 2>&1";
echo shell_exec("/bin/bash -c '" . $command. "'");
输出:
p
b
c
d
e
关于如果 php shell_exec 包含用于字符串替换的大括号,则它会默默失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66910945/