-1

My BASH command string ($@) looks like this: cmd -arg1 foo bar --flag1 --flag2

Flags come after args, and I don't have any awkward gotchas in the args (I am building an internal tool for my own use).

How can I extract -arg1 foo -arg2 bar into $args and --flag1 --flag2 into $flags?

1 Answer 1

0

The following works, although I suspect it is not optimal:


> echo $x
cmd -arg1 foo bar --flag1 --flag2

> flags="--${x#*--}"

> echo $flags
--flag1 --flag2

> before_flags=${x%%"$flags"}

> echo $before_flags
cmd -arg1 foo bar

> set $before_flags

> echo $1
cmd

> echo $2
-arg1

> echo $3
foo

> echo $4
bar

Ref: https://mywiki.wooledge.org/BashFAQ/100 -- How do I do string manipulations in bash?
Ref: https://mywiki.wooledge.org/BashFAQ/035 -- How can I handle command-line options and arguments in my script easily?

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

2 Comments

It looks like you're treating the argument list as a single space-delimited string, rather than a series of separate arguments (e.g. as an array). This will cause trouble if any arguments contain whitespace and/or filename wildcard characters. Also, it's more normal to have flags before regular arguments.
this doesn't work unless you know with 100% certainty that you'll always have options and flags provided in this same exact format, eg, the proposed code (obviously) does not work for x="cmd bar --flag2 -arg1 foo --flag1"; perhaps a nonsensical example but without some idea of the possible combos that you'll have to realistically deal with ...

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.