When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.
For example, copying a b
It may be achieved in a pretty simple way:
for
loop$bar
variable another =
sign to make the progress bar wider\r
cleans line and returns to the beginning of the line; -ne
makes echo
doesn't add newline at the end and parses \r
special character)function progress {
bar=''
for (( x=0; x <= 100; x++ )); do
sleep 0.25
bar="${bar}="
echo -ne "$bar ${x}%\r"
done
echo -e "\n"
}
$ progress
> ========== 10% # here: after 2.5 seconds
$ progress
> ============================== 30% # here: after 7.5 seconds
COLORED PROGRESS BAR
function progress {
bar=''
for (( x=0; x <= 100; x++ )); do
sleep 0.05
bar="${bar} "
echo -ne "\r"
echo -ne "\e[43m$bar\e[0m"
local left="$(( 100 - $x ))"
printf " %${left}s"
echo -n "${x}%"
done
echo -e "\n"
}
To make a progress bar colorful, you can use formatting escape sequence - here the progress bar is yellow: \e[43m
, then we reset custom settings with \e[0m
, otherwise it would affect further input even when the progress bar is done.