为什么' getopts'一个函数内部无法正常工作?

时间:2012-05-04 18:48:44

标签: bash ubuntu

function readArgs() {
    while getopts "i:o:p:s:l:m" OPTION; do
        case "$OPTION" in
            i)
                input="$OPTARG"
                ;;
            o)
                output="$OPTARG"
                ;;
            ...
        esac
    done
}

readArgs

if [[ -z "$input" ]]; then
    echo "Not set!"
fi

这总是给我Not set!,但如果我注释掉function readArgs() {}readArgs这一行,它就可以了。为什么呢?

此外,

input="$OPTARG"
echo "$input"
;;

不起作用。

2 个答案:

答案 0 :(得分:16)

getopts正在解析readArgs函数的参数,并且你没有给该函数任何参数。

尝试:

readArgs "$@"

答案 1 :(得分:8)

getopts依赖于OPTIND变量初始化为1.要么

readArgs() { OPTIND=1; ...

readArgs() { local OPTIND; ...