I have a script with a long list of OPTIONAL arguments. some have associated values.
Such as:
.script --first 2012-12-25 --last 2012-12-26 --copy --remove
.script --first 2012-12-25
Thus the following case statement:
for arg in "$@"
do
case $arg in
"--first" )
START_DATE=$arg;;
"--last" )
END_DATE=$arg;;
"--copy" )
COPY=true;;
"--remove" )
REMOVE=true;;
# ... and so on
esac
done
My problem:
that needs a increment $arg+1
type statement to get the following arg (in some cases).
How is that possible?
I'm also happy to do a substring such .script --first2012-12-25 --last2012-12-26
and not sure how to proceed there.
If you have more than one option, and especially options with values mixed with options without values, let getopts do the work for you.
getopts cannot have optional arguments it seems. otherwise great.
my solution
loop the
$@
and setting a variable equal tox=$arg
do the case switch on that variable (rather than arg)that worked fine for arguments of the type
--startdate 2012-12-25 --enddate 2012-12-29
but did not work for
--remove
that has no following argument.therefore tack on stuff (unlikely argument) onto the arg string.
leaving the following
... and so on....
You can allow both --a=arg or -a arg options with a little more work:
Note the --optional argument uses a default value if "=" is not used, else it sets the value in the normal way.
$@
is an array, & not a simple variable.You can capture it to a local variable as
x=("$@")
& then use array x with indices as0 to ($# - 1)
.To access individual elements, use
${x[$i]}
. You can NOT directly use${@[$i]}
, however.So instead of
for arg in "$@"
loop, you will havei=0; while [ $i -lt $# ]; do
loop.Use
shift
in the end of eachcase
statement.Quote from a
bash
manual: