Question

I have been trying to write a very basic generic bash option parser for one of my projects. The idea is as follows:

  • I feed a list of command-line arguments, some of them are options
  • I want to extract the options into a separate array
  • I will end up with two arrays:
    • One array for arguments
    • One array for options

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?

Was it helpful?

Solution

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[@]}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top