Zach Bloomquist
Zach Bloomquist

Reputation: 5871

Running a shell script in the background from PHP

The scenario:

  1. I have a PHP script (accessed via the web) which generates a shell script which needs to continue to run even after the request ends.
  2. I need the output sent to a file on disk (i.e. "./script.sh > run.log")

Every approach I try seems to result in PHP still waiting for the shell script to finish executing. Approaches I've tried:

  1. nohup ./script.sh > run.log &
  2. nohup ./script.sh > run.log 2>&1
  3. nohup ./script.sh > run.log 2>&1 &
  4. ./script.sh &
  5. ./script.sh > run.log 2>&1
  6. ./script.sh > run.log &

I think there's something really obvious I might be missing. Any ideas?

Upvotes: 1

Views: 2291

Answers (3)

Tim Penner
Tim Penner

Reputation: 3541

Your number 5 approach is close but you need to combine it with 6 like this

shell_exec("/script.sh > run.log 2>&1 &");

Or redirect to /dev/null like this

shell_exec("/script.sh > /dev/null 2>/dev/null &")

It appears that the PHP development server cannot fork off commands properly. Using a real web server like Apache or NGinx will resolve the issue.

Upvotes: 1

Have you tried shell_exec ?

You might be interested in this post : Is there a way to use shell_exec without waiting for the command to complete?

Upvotes: 1

tschoffelen
tschoffelen

Reputation: 520

I think you could achieve this by starting a screen instance with the script:

screen -d -m 'bash ./script.sh > run.log'

Upvotes: 2

Related Questions