title: Best way to parse command line args in Bash?
body: <p>After several days of <a href="http://wiki.bash-hackers.org/scripting/posparams">research</a>, I still can't figure out the best method for parsing cmdline args in a .sh script.  According to my references the getopts cmd is the way to go since it "<em>extracts and checks switches without disturbing the positional parameter variables.Unexpected switches, or switches that are missing arguments, are recognized and reportedas errors.</em>"  </p>
  
  <p>Positional params(Ex. 2 - $@, $#, etc)  apparently don't work well when spaces are involved but can recognize regular and long parameters(-p  and --longparam).  I noticed that both methods fail when passing parameters with nested quotes ("this is an Ex. of ""quotes"".").  Which one of these three code samples best illustrates the way to deal with cmdline args? The <strong>getopt</strong> function is not recommended by gurus, so I'm trying to avoid it!</p>
  
  <p><strong>Example 1:</strong></p>
  
  <pre><code>#!/bin/bash
  for i in "$@"
  do
  case $i in
      -p=*|--prefix=*)
      PREFIX=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
  
      ;;
      -s=*|--searchpath=*)
      SEARCHPATH=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
      ;;
      -l=*|--lib=*)
      DIR=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
      ;;
      --default)
      DEFAULT=YES
      ;;
      *)
              # unknown option
      ;;
  esac
  done
  exit 0
  </code></pre>
  
  <p><strong>Example 2:</strong></p>
  
  <pre><code>#!/bin/bash
  echo ‘number of arguments’
  echo "\$#: $#"
  echo ”
  
  echo ‘using $num’
  echo "\$0: $0"
  if [ $# -ge 1 ];then echo "\$1: $1"; fi
  if [ $# -ge 2 ];then echo "\$2: $2"; fi
  if [ $# -ge 3 ];then echo "\$3: $3"; fi
  if [ $# -ge 4 ];then echo "\$4: $4"; fi
  if [ $# -ge 5 ];then echo "\$5: $5"; fi
  echo ”
  
  echo ‘using $@’
  let i=1
  for x in $@; do
  echo "$i: $x"
  let i=$i+1
  done
  echo ”
  
  echo ‘using $*’
  let i=1
  for x in $*; do
  echo "$i: $x"
  let i=$i+1
  done
  echo ”
  
  let i=1
  echo ‘using shift’
  while [ $# -gt 0 ]
  do
  echo "$i: $1"
  let i=$i+1
  shift
  done
  
  [/bash]
  
  output:
  
  bash&gt; commandLineArguments.bash
  number of arguments
  $#: 0
  
  using $num
  $0: ./commandLineArguments.bash
  
  using $@
  
  using $*
  
  using shift
  #bash&gt; commandLineArguments.bash  "abc def" g h i j*
  </code></pre>
  
  <p><strong>Example 3:</strong></p>
  
  <pre><code>#!/bin/bash
  
  while getopts ":a:" opt; do
    case $opt in
      a)
        echo "-a was triggered, Parameter: $OPTARG" &gt;&amp;2
        ;;
      \?)
        echo "Invalid option: -$OPTARG" &gt;&amp;2
        exit 1
        ;;
      :)
        echo "Option -$OPTARG requires an argument." &gt;&amp;2
        exit 1
        ;;
    esac
  done
  
  exit 0
  </code></pre>