Jump to content

Bash output - is it possible to get "realtime" output?


ubuntu-user

Recommended Posts

Hello

 

I have a PHP web application that needs to run a bash script that takes around 15 seconds to run. What I need is for the bash script output - which outputs progress - to be displayed in my PHP web application in "realtime". i.e. each time bash outputs something, it is displayed in the users browser.

 

For the purpose of this thread, let's choose a bash example as follows:

 

COUNTER=1
while [ $COUNTER -le 10 ]; do
        echo "Counter: $COUNTER"
        COUNTER=$((COUNTER+1))
        sleep 1
done

 

As you can see, it will echo a counter number from 1 to 10, pausing for 1 second in between.

 

Now I can get this to display in my PHP application, but not in the same way it displays when running it directly in BASH.

 

echo "<pre>";
$cmd = "sh /usr/local/bin/test"; 
system($cmd);
echo "</pre>";

 

What typically happens is that output comes out as follows:

 

Counter: 1

Counter: 2

 

then

 

Counter: 3

Counter: 4

Counter: 5

Counter: 6

 

then

 

Counter: 7

Counter: 8

Counter: 9

Counter: 10

 

i.e. it is sporadic and not like the BASH output.

 

I've tried various PHP functions like exec, shell_exec and passthru.

 

Is this actually possible? I've seen it before in web applications when running BASH scripts, but they might have been Perl based.

 

This application is for internal use, so I have full access as admin to the server it's on.

 

I'm using:

Ubuntu 9.10

PHP 5.2.10

LightTPD for my server

 

Thanks

Link to comment
Share on other sites

Try something like this:

 

<?php
$handle = popen('sh /usr/local/bin/test', 'r');
while (!feof($handle)) {
        echo fgets($handle);
        flush();
        ob_flush();
}
pclose($handle);

 

Your webserver might still buffer output though. In that case there is nothing you can do from the PHP side.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.