Shell Script Loop from PHP not working

2019-07-28 02:11发布

问题:

I am trying to call a shell script loop using the shell_exec() php function but with no avail.

I can do shell_exec("ls") with no problem.

I can ssh to the server and do for f inls; do echo $f ; done with no problem.

But when I combine the two,

shell_exec("for f in `ls` ; do echo $f ; done")

I get nothing as output (nor NULL as error, I checked).

What am I missing here?

P.S: The for loop I am using here is not one I intend to use, it's just to make it clearer.

回答1:

echo shell_exec("for f in `ls` ; do echo \$f ; done");

Your mistakes:

  1. Missed echo
  2. $ sign should be escaped as soon as you're using double quotes (or double quotes may be replaced with single quotes instead)

Pro tip: always develop with error_reporting level E_ALL (or higher) and display_errors 1



标签: php shell