【问题标题】:php shell_exec silently fails if it contains curly brackets for string substitution如果 php shell_exec 包含用于字符串替换的大括号,它会静默失败
【发布时间】:2021-06-28 19:57:07
【问题描述】:

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

有什么问题??

谢谢

【问题讨论】:

  • 您的交互式 shell 可能是 bash,但 shell_exec 可能正在调用不理解模式替换参数扩展的 posix shell(例如 /bin/sh
  • @jhnc 谢谢,你对如何使它起作用有什么建议吗?
  • 直接在php中进行模式替换;将脚本保存到文件中并调用shell_exec('/bin/bash /path/to/script');致电exec('/bin/bash -c 'shell commands')
  • @jhnc 非常感谢!

标签: php shell


【解决方案1】:

正如@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

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 2021-12-01
    • 2020-07-26
    • 1970-01-01
    • 2020-06-12
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多