PHP CLI Status Indicator

21 May

Most times when people write command line scripts they just let the output flow down the screen as a status indicator, or just figure “it’s done when it’s done” But sometimes it would be nice to have a simple clean status indicator, allowing you to monitor progress and gauge time-to-completion. This is actually very easy to accomplish. Simply use \r instead of \r\n in your output. Obviously the example below is very simplified, and this can be applied in a much more sophisticated fashion. But it works.

<font style="color: darkred">$row_count = get_total_rows_for_processing();</font>
$limit=10000;
<font style="color: darkred">echo "&#92;r&#92;n[  0%]";</font>
for ( $i=0; $i &lt; = $row_count; $i = $i + $limit ) {
  $query="SELECT * FROM table LIMIT {$limit} OFFSET {$i}";
  // do whatever
  <font style="color: darkred">$pct = round((($i+$offset)/$row_count)*100);
  if ( $pct &lt; 10 ) {
    echo "&#92;r[  $pct%]";
  } else {
    if ( $pct &lt; 100 ) {
      echo "&#92;r[ $pct%]";
    } else {
      echo "&#92;r[$pct%]";
    }
  }</font>
}
<font style="color: darkred">echo "&#92;r[100%]&#92;r&#92;n";</font>

Leave a Reply

CodeWord: Apokalyptik

The random things that spew forth from my brain…