1

I found this cool progress bar I'm using: https://stackoverflow.com/a/27147177/1480397

But I have no clue what it is doing and I'm failing to google it.

"\r\033[0G\033[2K[%'={$percentageDone}s>%-{$percetageLeft}s] -   $percentageDone%% - $absoluteDone/$absoluteTotal - avg %.4f - %s",

This is what I'm using.

I think the sequences are:

  • \r - carriage return, go back to start
  • \033[0G - Esc[0g Clear a tab at the current column` *
  • \033[2K- Esc[2K Clear entire line *
  • [%'={$percentageDone}s>%-{$percetageLeft}s]

* This doesn't do what I expect, when I remove the code, Source: http://ascii-table.com/ansi-escape-sequences-vt-100.php

So, are these sequences extracted correctly? Is the interpretation correct? And why is the last writing cool bars?

[====>                                       <much more spaces>       ]

Code to test:

for ($i = 0; $i <= 100; $i++) {
    $absoluteDone = $i;
    $absoluteTotal = 100;
    $percentageDone = floor(($absoluteDone / $absoluteTotal) * 100);
    $percetageLeft = 100 - $percentageDone;
    $avgTime = 10;
    $setCursorToLineStart = "\033[0G";
    $clearLine = "\033[2K";
    $progressbarAndStatusInfo = sprintf(
        $setCursorToLineStart
        . $clearLine
        . "[%'={$percentageDone}s>%-{$percetageLeft}s] - $percentageDone%% - $absoluteDone/$absoluteTotal - avg %.4f - %s",
        "",
        "",
        $avgTime,
        gmdate("H:i:s", $avgTime * ($absoluteTotal - $absoluteDone))
    );

    echo $progressbarAndStatusInfo;
    sleep(1);
}
Community
  • 1
  • 1
Fabian Blechschmidt
  • 4,113
  • 22
  • 39
  • Please read [How to ask a good question](http://stackoverflow.com/help/how-to-ask) and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – RiggsFolly Dec 29 '15 at 16:05
  • Not sure what is wrong. I have four escape sequences which I need to understand? What is broad about this question? – Fabian Blechschmidt Dec 29 '15 at 16:07
  • 1
    provide context for the "code" (`sprintf` !) – Karoly Horvath Dec 29 '15 at 16:10
  • Looks like it's trying to mimic ncurses style updates. Write a line with various lengths of '=' followed by spaces to fill the line. Then carriage return, clear and repeat it. – ethrbunny Dec 29 '15 at 16:33

1 Answers1

1

The ansi escape codes look correct to me, however:

[%'={$percentageDone}s>%-{$percetageLeft}s]

has nothing to do with ansi. It's padding via sprintf:

'={$percentageDone}

will fill the line with x '=' chars, where x is the value in $percentageDone.

See sprintf docs for details.

Erik Dannenberg
  • 5,716
  • 2
  • 16
  • 21