Gosh Darn
Gosh Darn

Reputation: 41

Getopt: A flag using with multiple optargs

How can I use two arguments for one flag?

For example:

./xampl -c foo bar

would return:

foobar

I've looked a the source code of gnu cat and freebsd ls, but could not find any leads

I'm a C novice and a competent bash scripter.

Upvotes: 0

Views: 303

Answers (1)

paxdiablo
paxdiablo

Reputation: 881153

The standard getopt stuff has no way to do this, it allows for single-argument additions to an option (with :) like -cfoo (part of the option argument) or -c foo (in the next argument). This can also be optional if you use :: though I believe it then has to be an extension of the option argument itself, not a separate argument.

It has no way to take more than one argument after the option argument and combine them into a single option. You can surround them with quotes to force it into a single argument, such as:

-c "foo bar"

but that won't remove the spaces. Of course, there's nothing to stop you specifying directly what you seem to want, with a slightly modified:

-c foobar

In other words, I'm not clear why you actually need them to be separate, especially since you're going to combine them anyway.

No doubt you could modify getopt to do this such as allowing for something like abc[2,collapse] (rather than abc:) to specify that -c needs two arguments which should have spaces removed between them. But that seems like a fair bit of work for something it may just be easier to work around.

Upvotes: 1

Related Questions