Update command line output, i.e. for progress

I would like to show a performance indicator in a simple PHP script on the command line. Instead of seeing

Progress: 0% Progress: 1% etc... 

I would just like to change the number and replace the previous number, like for example git clone, for example Resolving deltas: 100% (8522/8522), done. .

While searching for this, I found the same question Perl answered , which is perfect, but I could not find it in PHP. Is it possible? If not, I will resort to C.

thank

Update: If anyone is interested in the C ++ version, here .

+42
command-line php stdout
Mar 10 2018-11-11T00:
source share
2 answers

This can be done using ANSI Escape Sequences - see here for a list.

In PHP, you will use "\033" if ESC specified on this page.


In your case, you can use something like this:

 echo "Progress : "; // 5 characters of padding at the end for ($i=0 ; $i<=100 ; $i++) { echo "\033[5D"; // Move 5 characters backward echo str_pad($i, 3, ' ', STR_PAD_LEFT) . " %"; // Output is always 5 characters long sleep(1); // wait for a while, so we see the animation } 


I simplified things a bit by making sure that I always have 5 extra characters and always displays the same amount of data to always move back the same number of characters ...

But, of course, you should be able to do a lot harder if necessary; -)

And there are many other interesting escape sequences: colors, for example, can slightly improve your output; -)

+85
Mar 10 '11 at 20:19
source share

Just for the record, although the old thread: Instead of using the fantastic ANSI Escape sequence to move the cursor backward, I will just put it back to the beginning of the line using "\ r" and not to the beginning of the next line "\ n". Add a few spaces after the echo to overwrite everything that was previously, for example, for example. So:

 for ($i=0 ; $i<=100 ; $i++) { echo "Progress: $i % \r"; sleep(1); } 
+19
Nov 13 '16 at 9:31
source share



All Articles