linux - getopts won't call twice in a row? -
for reason options work fine first call of lib_progress_bar -c "@" -u "_" 0 100
, on second call , beyond default because seems getopts c:u:d:p:s:%:m: flag
isn't true second time around, or atleast case never executed when used set -x
#!/bin/bash lib_progress_bar() { local current=0 local max=100 local completed_char="#" local uncompleted_char="." local decimal=1 local prefix=" [" local suffix="]" local percent_sign="%" local max_width=$(tput cols) local complete remain subtraction width atleast percent chars local padding=3 while getopts c:u:d:p:s:%:m: flag; case "$flag" in c) completed_char="$optarg";; u) uncompleted_char="$optarg";; d) decimal="$optarg";; p) prefix="$optarg";; s) suffix="$optarg";; %) percent_sign="$optarg";; m) max_width="$optarg";; esac done shift $((optind-1)) current=${1:-$current} max=${2:-$max} if (( decimal > 0 )); (( padding = padding + decimal + 1 )) fi let subtraction=${#completed_char}+${#prefix}+${#suffix}+padding+${#percent_sign} let width=max_width-subtraction if (( width < 5 )); (( atleast = 5 + subtraction )) echo >&2 "the max_width of ($max_width) small, must atleast $atleast" return 1 fi if (( current > max ));then echo >&2 "current value must smaller max. value" return 1 fi percent=$(awk -v "f=%${padding}.${decimal}f" -v "c=$current" -v "m=$max" 'begin{printf('f', c / m * 100)}') (( chars = current * width / max)) # sprintf n zeros var named arg -v printf -v complete '%0*.*d' '' "$chars" '' printf -v remain '%0*.*d' '' "$((width - chars))" '' # replace zeros desired char complete=${complete//0/"$completed_char"} remain=${remain//0/"$uncompleted_char"} printf '%s%s%s%s %s%s\r' "$prefix" "$complete" "$remain" "$suffix" "$percent" "$percent_sign" if (( current >= max )); echo "" fi } lib_progress_bar -c "@" -u "_" 0 100 echo lib_progress_bar -c "@" -u "_" 25 100 echo lib_progress_bar -c "@" -u "_" 50 100 echo exit;
just add:
local optind
at top of function.
Comments
Post a Comment