2

The getopts command doesn't seem to work in a function. Maybe I did something wrong. The code below is what I have now. it is working if I put the whole while loop outside function. I am wondering if there is a way to make getopts work with functions ? I am new to the shell script. Any help would be appreciated :)

getOptions()
{
    while getopts :al:f:vd opt; do
            case "$opt" in
                    l) logFile = $OPTARG ;;
                    f) fileTable = $OPTARG ;;
                    v) verbose = 1 ;;
                    d) set -x ;;
                    a) echo "a";;
                    \?) echo "Invalid option: -$opt";;
            esac
    done
    shift $(($OPTIND - 1))
}

1 Answer 1

4

One reason might be your usage of things like logFile = $OPTARG when you shouldn't have any spaces there (it should read logFile=$OPTARG).

Another reason is the fact that $1, $2, etc. are all referring to the function's arguments, not the shell script's arguments. Since the shell works that way, and getopts uses $1, $2, etc., you're using the function's arguments with getopts, not the script's arguments. In other words, confining your option processing to a shell function is not a good idea.

Sign up to request clarification or add additional context in comments.

2 Comments

+1; I guess it's fine to use a function if you invoke it with getOptions "$@" to pass the script's arguments through.
That makes sense. Thank you so much! I always forget not to put spaces in between ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.