如果 php shell_exec 包含用于字符串替换的大括号,则它会默默失败

标签 php shell

这个简单的命令如果粘贴到终端中可以正常工作,但在 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/

相关文章:

mysql - 在 shell 脚本中执行 mysql 查询

php - 如何在yii2中制作下拉列表?

php - 提交表单后如何在选择框上保持输入值

javascript - 用户单击使用按钮后更新表

php - 使用 soundex() 或 metaphone() 创建 Mad Gab 风格短语的算法

python - "killall python"后看不到键盘输入

bash - ln -s 覆盖物理目录

database - 通过命令行插入 SQL 语句而无需重新打开与远程数据库的连接

bash - 来自反引号的多字参数(命令替换)

php - 即使查询不匹配,Mysql 结果也会重复