Simulare una progressbar (Bash shell)…
Salve gente.
Spesso mi trovo a scrivere ed usare script di shell che effettuano operazioni particolarmente lunghe, talvolta senza nemmeno un output e nemmeno un qualche indice di avanzamento (cfr. bel post di Stefano).
Così, per rendere chiaro lo stato di avanzamento di un’operazione ho trovato comodo ed opportuno scrivere questo piccolo script Bash che simula una progressbar, ispirata da quella del celebre comando di trasferimento sicuro scp.
Penso che il codice sia sufficientemente corto e chiaro nonchè portabile su altre shell e, perchè no, in altri linguaggi. Spero anche che vi piaccia.
Ciau!
Il codice
# FILE : Progressbar.sh
# AUTHOR : Gian Paolo "JP" Ghilardi
# LICENSE : GPL v2.0 (only)
# PURPOSE : show a simple progressbar-like "animation" (Bash script)
# USAGE : ./progressbar.sh
#
# TESTED ON :
# - Windows XP, x86 32-bit, Bash 3.2.48 (MinGW)
# - Linux, x86 32-bit, Bash 2.05a
# - MacOSX, PPC 32-bit, Bash 3.2.17(1)
#
# EXAMPLE : (output of the command)
# [user@box PBar]$ ./progressbar.sh
# SIMPLE SHELL (BASH) EXAMPLE:
# Progressbar-like animation.
# Detected TTY columns: 80
# [ 67%] ################################################
#
#! /bin/bash
# determine TTY (terminal) max columns
TCOLS=$(stty -a | tr -s ';' '\n' | grep "column" | sed s/'[^[:digit:]]'//g)
PBMIN=0 # progressbar min value
PBMAX=100 # progressbar max value
PBSYM="#" # symbol used for building the progressbar
PBPERCLEN=7 # length of % string, i.e. "[100%] " => 7 chars
# create the progressbar
function GetPBLine()
{
PBVAL=$1 # current progressbar value (function param)
PBUCOLS=$(($TCOLS-$PBPERCLEN)) # usable columns
PBNUM=$((($PBVAL*$PBUCOLS)/($PBMAX-$PBMIN)))
for((j=0; j<$PBNUM; j++)); do
PBLINE="$PBLINE$PBSYM"
done
PBPERC=$(printf "[%3d%%] " $PBVAL) # i.e. "[ 12%] "
echo -ne "$PBPERC$PBLINE\r"
}
echo "SIMPLE SHELL (BASH) EXAMPLE:"
echo "Progressbar-like animation."
echo "Detected TTY columns: $TCOLS"
# loop showing progressbar "animation"
for((i=$PBMIN; i<=$PBMAX; i++)); do
echo -ne "$(GetPBLine $i)\r"
# do something (i.e. a step of a long computation)
done
echo -e "\nJob done!"
Il codice dal vivo
Ciau!
Categories: BASH, LinkedIn, Linux, Mac, Programmazione, Script, Shell, Windows
BASH, MacOSX, Windows, Linux, LinkedIn, Shell script, Progressbar


Commenti Recenti