title: Combine autocomplete with getopts
body: <p>I made a script called "gc" to autocomplete git branch names, when using the <code>git checkout</code> functionality, e.g. typing <code>gc mob-102</code> then pressing tab twice would display matching branch names such as mob-1025-a, mob-1025-b, mob-1021-end, etc.  </p>
  
  <pre><code>function gc() {
    git checkout "$1"
  }
  
  _gc() {
      COMPREPLY=()
      cur="${COMP_WORDS[COMP_CWORD]}"
      local branch_names=$(git branch|xargs basename|grep -v '*')
      local tag_names=$(git tag)
      local remote_branch_names=$(git branch -r|xargs basename|grep -Ev "HEAD|-&gt;")
      local all_branch_and_tag_names=${branch_names}${remote_branch_names}${tag_names}
      COMPREPLY=($(compgen -W "${all_branch_and_tag_names}" $cur))
  }
  complete -F _gc gc
  </code></pre>
  
  <p>I put this into my .bash_profile, and that was fine. However, now I'm trying to add an optional "-b" option, so that you can also have the <code>git checkout -b &lt;new branch name&gt;</code> functionality, i.e. create a new branch from the current branch, e.g. 
  <code>gc -b my_new_branch</code>.  If you don't pass the "-b" option, I'd want the autocomplete to work as before.</p>
  
  <p>I've used <code>getopts</code> before in other scripts, but I can't seem to get this to work.  One approach I tried was:</p>
  
  <pre><code>    function gc() {
          if [[ $# -gt 1 ]]
          then
            echo "There is more than one argument on the command line"
            while getopts ":b:" opt; do
              echo "Got an option: $OPTARG"
              case $opt in
                b)
                  echo "Got the -b option with $OPTARG"
                  git checkout -b "$OPTARG"
                  ;;
               \?)
                 echo "Invalid option: -$OPTARG" &gt;&amp;2
                 exit 1
                 ;;
              esac
            done
         else
            gc_branch_complete "$1"
         fi
      }
  
  function gc_branch_complete() {
      git checkout "$1"
  }
  
  _gc() {
      COMPREPLY=()
      cur="${COMP_WORDS[COMP_CWORD]}"
      local branch_names=$(git branch|xargs basename|grep -v '*')
      local tag_names=$(git tag)
      local remote_branch_names=$(git branch -r|xargs basename|grep -Ev "HEAD|-&gt;")
      local all_branch_and_tag_names=${branch_names}${remote_branch_names}${tag_names}
      COMPREPLY=($(compgen -W "${all_branch_and_tag_names}" $cur))
  }
  complete -F _gc gc_branch_complete
  </code></pre>
  
  <p>Oddly, this seemed to work when run the first time, but not on subsequent invocations.</p>
  
  <p>Are there any better approaches than this?</p>