getopts连续调用两次会出现问题吗?

12

由于某种原因,在第一次调用 lib_progress_bar -c "@" -u "_" 0 100 时选项正常工作,但在第二次及以后的调用中,所有内容都是默认值,因为好像第二次周围的 getopts c:u:d:p:s:%:m: flag 不是真实的,或者至少在我使用 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; do
        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 )); then
        (( padding = padding + decimal + 1 ))
    fi


    let subtraction=${#completed_char}+${#prefix}+${#suffix}+padding+${#percent_sign}
    let width=max_width-subtraction


    if (( width < 5 )); then
        (( atleast = 5 + subtraction ))
        echo >&2 "the max_width of ($max_width) is too small, must be atleast $atleast" 
        return 1 
    fi


    if (( current > max ));then
        echo >&2 "current value must be smaller than 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 into the var named as the arg to -v
    printf -v complete '%0*.*d' '' "$chars" ''
    printf -v remain '%0*.*d' '' "$((width - chars))" ''

    # replace the zeros with the 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 )); then
        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;
2个回答

16

只需添加:

local OPTIND

在你的函数顶部。


1
我在 getopts-while 循环和 shift 后使用 OPTIND=0。我不知道 local OPTIND 的技巧,但如果您在同一函数中奇怪地调用 getopts 多次,则零重置应该可以正常工作。 - Toddius Zho

14
为了解释Dennis的答案如何有效,可以查看bash手册(搜索getopts):
OPTIND在每次调用shell或shell脚本时都会初始化为1。
Shell不会自动重置OPTIND;如果要使用新的参数集,在同一次shell调用中多次调用getopts时必须手动重置它。
这就是getopts如何处理多个选项的方法。
如果getopts没有在OPTIND变量中维护全局状态,那么您在while循环中对getopts的每次调用将继续处理$1,并且永远不会前进到下一个参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接