php shell_exec silently fails if it contains curly brackets for string substitution

Viewed 143

This simple command works fine if pasted in the terminal but in php it doesn't work.

for f in a b c d e; do echo ${f/a/p}; done; 2>&1

Terminal

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);

outputs nothing.

$command = "for f in a b c d e; do echo \$\{f/a/p\}; done;";
$command .= " 2>&1";
echo shell_exec($command);

output:

${f/a/p}
${f/a/p}
${f/a/p}
${f/a/p}
${f/a/p}

What's the problem??

Thanks

1 Answers

as @jhnc mentioned, the problem is it uses shell instead of bash. You can execute bash with command argument like this:

$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. "'");

Output:

p
b
c
d
e
Related