I have been trying to write a very basic generic bash option parser for one of my projects. The idea is as follows:
NOTE: I do not care about optional options and options that take arguments. For my purposes, all options are switches.
Here is the code I have at the moment:
parse() {
options=()
arguments=()
for arg
do
if [[ $arg = -* ]]
then
options+=("$arg")
else
arguments+=("$arg")
fi
done
echo $options
echo $arguments
}
# $ parse --one --two -v "FOO" "BAR"
# => --one
# => FOO
The problem, as you can see in the output, is that only the first option and the first argument are stored in the array.
What am I doing wrong please?
Parsing and storing is OK, output is wrong: you are only printing the first element of the arrays.
See "Arrays" in man bash
for proper syntax:
echo "${options[@]}"
echo "${arguments[@]}"