简体   繁体   中英

Shell script to loop command line switches and arguments

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?

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

arg1=$1; shift
arg2=$1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM