2

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
  • Turn on errors, and set error reporting to E_ALL - you have at least a notice here Commented May 30, 2013 at 0:27

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

6 Comments

how does it pick which shell to use?
@j_mcnally: that's actually an interesting question. I honestly don't know and haven't thought about that ever
Internally it uses (for linux) popen, but not sure how it picks the shell in case if current user don't have any assigned (/bin/false)
@j_mcnally: seems like the one that was used to run the webserver (or current user's if run by CLI)
I posted this as a question if you want to chime in. stackoverflow.com/questions/16826223/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.