user2326674
user2326674

Reputation: 11

Parsing mixed arguments in a script bash

I need to implement a script called with mixed (optional and non-optional) arguments for example -

./scriptfile -m "(argument of -m)" file1 -p file2 -u "(argument of -u)" 

in a random order. I've read a lot about the getopts builtin command, but I think it doesn't solve my problem. I can't change the order of arguments, so I don't understand how I can read the arguments one by one.
Someone have any ideas?

Upvotes: 1

Views: 365

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185831

You should really give a try to getopts, it is designed for that purpose :

Ex :

#!/bin/bash

while getopts ":a:x:" opt; do
  case $opt in
    a)
      echo "-a was triggered with $OPTARG" >&2
    ;;
    x)
      echo "-x was triggered with $OPTARG" >&2
    ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
    ;;
  esac
done

Running the script with different switches ordering :

$ bash /tmp/l.sh -a foo -x bar
-a was triggered with foo
-x was triggered with bar

$ bash /tmp/l.sh -x bar -a foo
-x was triggered with bar
-a was triggered with foo

As you can see, there's no problem to change the order of the switches

See http://wiki.bash-hackers.org/howto/getopts_tutorial

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249642

Consider using Python and its excellent built-in library argparse. It will support almost any reasonable and conventional command line options, and with less hassle than bash (which is, strangely, a fairly poor language when it comes to command line argument processing).

Upvotes: 0

Related Questions