In a bash script, I need to parse arguments that have the following form:
The main arguments can be thought of as being a single argument, but I do not want to force users to quote the entire thing, so when the argument contains spaces I must be able to handle multiple arguments.
One flag may be passed as
-<flag>
where<flag>
can be an arbitrary word (without spaces)Finally, an external command, including its own options and flags may be passed. If so, this should be separated by a double dash.
For example,
my_command test
should result in
"$inp" == "test"
"$flag" == ""
"$ext_command" == ""
and
my_command this is a test -new -- sed "s|a|b|"
should result in
"$inp" == "this is a test"
"$flag" == "new"
"$ext_command" == "sed \"s|a|b\""
I think the following script does what I want, but since it's my first bash script, I wanted to ask whether the script is idiomatic and whether I missed any border cases.
local inp=""
local flag=""
local ext_command=""
local count="1"
local started=""
for i
do
count=$((count+1))
if [[ "$i" == '--' ]]
then
ext_command="${@:count}"
break
else
if [[ "$i" == -* ]];
then
flag=${i#*-}
else
if [ ! "$started" ]
then
inp="$i"
started=1
else
inp="$inp $i"
fi
fi
fi
done