Progressbar fo shell apps

This is a porting to PHP of Ruby code showed here .

def print_progress_bar(finished_percent)
  fixed_space = 9 # for braces and number
  width = `tput cols`.to_f - fixed_space
  finished_count = ((finished_percent*width)/100).ceil
  empty_count    = width - finished_count
  finished = "#" * finished_count
  empty    = "-" * empty_count
  print "\r[ #{finished}#{empty} ] #{finished_percent}% "
end
(0..100).each do |count|
  print_progress_bar(count)
  sleep 1
end

Hope you find it useful.

function print_progress_bar($finished_percent, $width=80 ) {
  $finished_percent = str_pad($finished_percent, 2, ' ');
  $fixed_space = 9; // for spaces, braces [ and number %
  $width -= $fixed_space;
  $finished_count = ceil( (($finished_percent*$width)/100) );
  $empty_count    = $width - $finished_count;
 
  $finished = str_repeat("#", $finished_count);
  $empty    = str_repeat("-", $empty_count);
 
  echo "\r[ {$finished}{$empty} ] {$finished_percent}% ";
}
$width = intval(`tput cols`);
foreach( range(0,100) as $count){
  print_progress_bar($count, $width);
  sleep(1);
}

but on the same theme i've made an adaptation that calculates the completion percentage

// print a progrss bar for the terminal
function show_progress(float $current, float $total, array $opt = []): void{
    // conf
    $option = array_merge([
        'bar_size' => 50,
        'char_done' => "#",
        'char_todo' => "-",
    ], $opt);
    extract($option);
    // input check
    if (empty($current) || empty($total)) {
        $msg = sprintf('Error invalid params %s %s', $current, $total);
        throw new \Exception($msg);
    }
    // calculate the progress in percentage
    $progress_perc = (100 * $current) / $total;
    // The number of done and todo characters
    $f_done = $bar_size * ($progress_perc / 100);
    $f_todo = $bar_size - $f_done;
    // build the done and todo sub-bars
    $s_done_sub_bar = str_repeat($char_done, (int) floor($f_done));
    $s_todo_sub_bar = str_repeat($char_todo, (int) floor($f_todo));
    // formatter
    $_fmt_perc = function (float $progress_perc, $n = 5): string{
        $s = number_format($progress_perc, 2, ',', '.');
        return str_pad($s, $n, '0', STR_PAD_LEFT) . '%';
    };
    // output the bar
    echo "\r"
    . sprintf("Progress: [%s%s] (%s of %s) %s",
        $s_done_sub_bar, $s_todo_sub_bar,
        $current, $total,
        $_fmt_perc($progress_perc)
    );
    if ($total == $current) {
        echo "\n" . "DONE";
    }
}

bash version that calculates the complation percentage:

#!/bin/bash
show_progress() {
    # conf
    local bar_size=${3:-50}
    local char_done=${4:-"#"}
    local char_todo=${5:-"-"}
    #
    current="$1"
    total="$2"
    # input check
    if [ -z "$current" ] || [ -z "$total" ]; then
        local msg="Error invalid params $current $total"
        die "$msg"
    fi
    # calculate the progress in percentage
    local progress_perc=$(echo "scale=2; 100 * $current / $total" | bc -l)
    # The number of done and todo characters
    local f_done=$(echo "scale=2; $bar_size * ($progress_perc / 100)" | bc -l)
    local f_todo=$(echo "scale=2; $bar_size - $f_done" | bc -l)
    # build the done and todo sub-bars by str_repeat
    local s_done_sub_bar=$(printf "%${f_done}s" | tr " " "${char_done}")
    local s_todo_sub_bar=$(printf "%${f_todo}s" | tr " " "${char_todo}")
    # output the bar
    printf "\rProgress: [%s%s] (%s of %s) %s" "$s_done_sub_bar" "$s_todo_sub_bar" "$current" "$total" "${progress_perc}%"
    if [ $total -eq $current ]; then
        echo -e "\n" "DONE"
    fi
}
die() {
    echo "$1"
    exit 1
}
tasks_in_total=26
for current_task in $(seq $tasks_in_total)
do
    sleep 0.2 #simulate the task running
    show_progress $current_task $tasks_in_total
done
exit 0

Tags:
PHP Ruby Bash

Blog Disclaimer:

Le opinioni espresse nel mio blog sono solo questo: mie opinioni.

In nessun modo rappresento le opinioni dei miei clienti in questa sede.


Notice: Undefined variable: browserName in /var/www/taziomirandola.it/lib/Visitors.php on line 86

Notice: Undefined variable: browserName in /var/www/taziomirandola.it/lib/Visitors.php on line 96

Deprecated: strripos(): Non-string needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the current behavior in /var/www/taziomirandola.it/lib/Visitors.php on line 96

Notice: Undefined index: HTTP_ACCEPT_LANGUAGE in /var/www/taziomirandola.it/lib/Visitors.php on line 39

Fatal error: Uncaught TypeError: Argument 1 passed to safe_text() must be of the type string, null given, called in /var/www/taziomirandola.it/lib/Visitors.php on line 39 and defined in /var/www/taziomirandola.it/lib/Visitors.php:162 Stack trace: #0 /var/www/taziomirandola.it/lib/Visitors.php(39): safe_text() #1 /var/www/taziomirandola.it/lib/Visitors.php(124): Visitors::getData() #2 [internal function]: Visitors::log() #3 {main} thrown in /var/www/taziomirandola.it/lib/Visitors.php on line 162