0

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?

Robert Audi
  • 8,019
  • 9
  • 45
  • 67

1 Answers1

3

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[@]}"
choroba
  • 231,213
  • 25
  • 204
  • 289