In Bash, why does using getopts in a function only work once? [duplicate]

a 夏天 提交于 2019-12-20 03:10:11

问题


I'm trying to create a simple function on macOS Sierra that counts the characters in a string. This works fine (added to my bashrc file):

function cchar() {
    str=$1
    len=${#str}
    echo "string is $len char long"
}

$ cchar "foo"
string is 3 char long

I'm trying to expand it with a -a option, so I added this to my function (and commented the rest out for testing):

while getopts "a:" opt; do
    case $opt in
        a)
            echo "-a param: $OPTARG" >&2
            ;;
    esac
done

After some testing while writing this, I've noticed everytime I run cchar -a "test", I have to run it without options (cchar) otherwise the next time I run it with the -a option, it doesn't recognise the option.

$ cchar

$ cchar -a "foo"
-a param: foo

$ cchar -a "foo"

$ cchar

$ cchar -a "foo"
-a param: foo

回答1:


You have to reset the variable OPTIND, which keeps track of the current positional argument number. It should suffice to make that variable local to your function.




回答2:


The final code I ended up using:

# Count characters in a string
function cchar() {
    local OPTIND

    while getopts "a:" opt; do
        case $opt in
            a)
                echo ${#OPTARG}
                return
                ;;
        esac
    done

    echo "string is ${#1} characters long"
}

$ cchar "foo bar"
string is 7 characters long

$ cchar -a "foo bar"
7

Note: I had to use return in lieu of exit, when sourced from .bashrc, exit will close the current shell.



来源:https://stackoverflow.com/questions/42336595/in-bash-why-does-using-getopts-in-a-function-only-work-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!