1

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?

2
  • please paste your code. Commented Apr 27, 2013 at 11:26
  • getopts is exactly what you need. Commented Apr 27, 2013 at 15:38

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.