1

I'm trying to write a bash script that will check command line switchess and use the very next argument for the switches argument.

Example:

sh myprogram.sh -s switchArg -p programArg start

Within my script I'm trying to loop it this way:

if [ "$#" -gt 2 ]
then
{
    i=1
    for arg in "$@"
    do
      if [ "$arg" == "-s" ] || [ "$arg" == "-S" ]
      then
      {
          i=$((i++))
          myArg=$i  # This then gets used later in my script
          continue
      }
      elif [ "$arg" == "-p" ] || [ "$arg" == "-P" ]
      then
      {
         i=$((i++))
         myArg2=$i  # This then gets used later in my script
         continue
      }
      else
      {
         echo "illegal option: $arg"
      }
   done

   do stuff
}
fi

How can I detect a switch and use the very next arg for the argument of the switch regardless of the amount of switches?

nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • 1
    have a look at http://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash and http://stackoverflow.com/questions/14152712/argument-parsing-in-bash and http://stackoverflow.com/questions/9271381/how-can-i-parse-long-form-arguments-in-shell and a whole bunch of others... – Fredrik Pihl May 09 '13 at 18:49
  • Thanks, that looks like the golden ticket. – nullByteMe May 09 '13 at 18:51
  • 1
    You do realize the `{` and `}` are unnecessary, right? They seem to have made you forget the `fi` inside the `for` loop. – chepner May 09 '13 at 19:04
  • 1
    This answer http://stackoverflow.com/a/16454668/632407 does exactly what you want. only replace "a" and "b" in the `getopts` and `case` to "s" and "p" – clt60 May 09 '13 at 20:05

1 Answers1

2

You can use "shift" which will remove the first parameter..
For instance:

arg1=$1; shift
arg2=$1