Shane
Shane

Reputation: 25

Is there a way to have a string as a switch using getopts?

I am seeing if there is a way for getopts to handle switches with strings instead of characters.

For example, I would like to supply something like this:

script.ksh -file1 file1.txt -file2.txt

Instead of:

script.ksh -f file1.txt -g file2.txt

Is this possible with unix getopts?

Upvotes: 1

Views: 280

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360153

The external getopt (note no "s") can handle long options, but it has its own disadvantages.

From BashFAQ/035:

Never use getopt(1). getopt cannot handle empty arguments strings, or arguments with embedded whitespace. Please forget that it ever existed.

Upvotes: 1

Philipp
Philipp

Reputation: 49832

No, it's not possible with getopts. You must do your own parsing, e.g. with a case switch:

while (($# > 0))
do
    case "$1" in
    -file1)
        shift
        file1=$1;;
    -file2)
        shift
        file2=$1;;
    esac
    shift
done

Upvotes: 1

Related Questions