Get Options and Parameters

Hi there.

Could someone explain how do i get the options separated from the arguments. My problem is that i have a lot of options and in all of those options i need to have the parameters available to use in that option and all the others. How can i take the arguments before i cycle throw the options?

Thanks in advance.

Hi.

Perhaps you're looking for getopts?

man getopts

(it's a built-in feature, so search for getopts)

Example

while getopts a:bc: ARG; do
case "$ARG" in
a) echo Option A with $OPTARG;;
b) echo Option B;;
c) echo Option C with $OPTARG;;
esac
done

./Test -a argument_a -b -c argument_c
 
Option A with argument_a
Option B
Option C with argument_c

A colon after the a and c (getopts a:bc:) means that the option takes an argument.

If your arguments have more than one word, put the words in quotes.

./Test -a "argument a" -b -c "argument c"
 
Option A with argument a
Option B
Option C with argument c

That is a good example thank you.
But that's not the example that I have. I have something like this

MyScript.sh -sd -r -e Dir1/Dir2 Dir3/Dir4

This exemplifies that MyScript receives one or more options and one or more directories (the arguments for the script are folders where I need to look for files according to the options).
First I have the options and after that I have the arguments. But after I run the first option I have to have all the arguments already available in a variable or something. Is there a way to accomplish this without the getops? I know i have to use shift.

[highlight=bash]
#set -A ARGS $( echo "$@" | sed "s/.-[a-z]\+ //")
ARGS=( $( echo "$@" | sed "s/.
-[a-z]\+ //") )

echo "Args: ${ARGS
[*]}"
echo "Arg 1: ${ARGS[0]}"
echo "Arg 2: ${ARGS[1]}"

while test "$1"; do
case "$1" in
-sd) echo Option sd;;
-r) echo Option r;;
-e) echo Option e;;
*) break;;
esac
shift
done

./Test -sd -r -e Dir1/Dir2 Dir3/Dir4
Args: Dir1/Dir2 Dir3/Dir4
Arg 1: Dir1/Dir2
Arg 2: Dir3/Dir4
Option sd
Option r
Option e

[/highlight]

Wow cool man. Thanks a lot. You have helped a lot. :wink: