Skip to content

Instantly share code, notes, and snippets.

@wenijinew
Created October 3, 2023 11:20
Show Gist options
  • Save wenijinew/5016b9d52c2dabd4ff38c1be41b2aa08 to your computer and use it in GitHub Desktop.
Save wenijinew/5016b9d52c2dabd4ff38c1be41b2aa08 to your computer and use it in GitHub Desktop.
Progress Bar in Bash
#!/usr/bin/bash
# source: https://stackoverflow.com/questions/238073/how-to-add-a-progress-bar-to-a-shell-script/68298090#68298090
percentBar () {
local prct totlen=$((8*$2)) lastchar barstring blankstring;
printf -v prct %.2f "$1"
((prct=10#${prct/.}*totlen/10000, prct%8)) &&
printf -v lastchar '\\U258%X' $(( 16 - prct%8 )) ||
lastchar=''
printf -v barstring '%*s' $((prct/8)) ''
printf -v barstring '%b' "${barstring// /\\U2588}$lastchar"
printf -v blankstring '%*s' $(((totlen-prct)/8)) ''
printf -v "$3" '%s%s' "$barstring" "$blankstring"
}
@wenijinew
Copy link
Author

    ((prct=10#${prct/.}*totlen/10000, prct%8)) &&
        printf -v lastchar '\\U258%X' $(( 16 - prct%8 )) ||
            lastchar=''

I don't understand ((prct=10#${prct/.}*totlen/10000, prct%8))

@wenijinew
Copy link
Author

wenijinew commented Oct 3, 2023

Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used.

That answers the question: what does 10# mean in the expression 10#${prct/.}*totlen/10000?

https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html

@wenijinew
Copy link
Author

https://mywiki.wooledge.org/ArithmeticExpression

You may use commas to separate multiple expressions within a single math context. The final value of the arithmetic expression is that of the last comma-delimited expression.

That explains ',' between prct=10#${prct/.}*totlen/10000 and prct%8

@wenijinew
Copy link
Author

for i in {0..10000..33} 10000;do i=0$i
    printf -v p %0.2f ${i::-2}.${i: -2}
    percentBar $p $((COLUMNS-9)) bar
    printf '\r|%s|%6.2f%%' "$bar" $p
    read -srt .002 _ && break    # console sleep avoiding fork
done

What does the underscore in read -srt .002 _ mean?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment