Gabe Rainbow Gabe Rainbow - 5 months ago 24
Bash Question

bash argument case for args in $@

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?

im also happy to do a substring such as
.script --first2012-12-25 --last2012-12-26

and not sure how to proceed there.

thanks.

Answer

getopts cannot have optional arguments it seems. otherwise great.

my solution

loop the $@ and setting a variable equal to x=$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

argc="$@ jabberwhocky" 
echo $argc
x=0
# x=0 for unset variable
for arg in $argc
do
   case $x in
        "--start" )
          STARTDATE=$arg ;;
        "--end" )
          ENDDATE=$arg ;;
        "--copy" )
          COPY=true;;
        "--remove" )
          REMOVE=true;;

... and so on....

    esac
    x=$arg
done
Comments