I have an if-testing construct for a bash-progress bar:
progress_bar () {
PROGRESS=`expr $( cat $CONTROL_FILE ) - 100 | tr "-" "\r"`
clear
if [ "$PROGRESS" -eq 10 ]
then
echo -n "$PROGRESS % [# ] "
fi
if [ $PROGRESS -eq 20 ]
then
echo -n "$PROGRESS % [## ] "
fi
if [ $PROGRESS -eq 30 ]
then
echo -n "$PROGRESS % [### ] "
fi
if [ $PROGRESS -eq 40 ]
then
echo -n "$PROGRESS % [#### ] "
fi
if [ $PROGRESS -eq 50 ]
then
echo -n "$PROGRESS % [##### ] "
fi
if [ $PROGRESS -eq 60 ]
then
echo -n "$PROGRESS % [###### ] "
fi
if [ $PROGRESS -eq 70 ]
then
echo -n "$PROGRESS % [####### ] "
fi
if [ $PROGRESS -eq 80 ]
then
echo -n "$PROGRESS % [######## ] "
fi
if [ $PROGRESS -eq 90 ]
then
echo -n "$PROGRESS % [######### ] "
fi
if [ $PROGRESS -eq 100 ]
then
echo "$PROGRESS % [##########]"
fi}
It works well: A "#" will be added each time when 10 are counted. My question is: Is there a way to make this look more beautiful? Like a for-loop or something else?
Thanks
CodePudding user response:
Would you please try the following:
progress_bar() {
local progress n bar
progress=$(expr $(<"$CONTROL_FILE") - 100 | tr "-" "\r")
clear
n=$(( $progress / 10 ))
if (( $progress > 0 )); then
bar=$(printf "%${n}s" " " | tr " " "#")
fi
printf "%s %% [%s]" "$progress" "$bar"
(( $progress >= 100 )) && echo # put newline when done
}
printf "%${n}s" " " | tr " " "#"
repeats a whitespace$n
times, then relace them with#
s of the same count.- As it is not recommended to use uppercases for user's variables, I've
changed
PROGRESS
toprogress
.
CodePudding user response:
I'd do it like this:
progress_bar () {
local percent hashes
hashes='##########'
percent=$(<"$CONTROL_FILE")
printf '\r%d %% [%-10s] ' $((100 - percent)) "${hashes:percent/10}"
}