Parsing getopts in bash

Posted by ABach on Stack Overflow See other posts from Stack Overflow or by ABach
Published on 2010-05-21T22:29:14Z Indexed on 2010/05/21 22:30 UTC
Read the original article Hit count: 269

Filed under:
|
|

I've got a bash function that I'm trying to use getopts with and am having some trouble.

The function is designed to be called by itself (getch), with an optional -s flag (getch -s), or with an optional string argument afterward (so getch master and getch -s master are both valid).

The snippet below is where my problem lies - it isn't the entire function, but it's what I'm focusing on:

getch()
{
  if [ "$#" -gt 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage: $0 [-s] [branch-name]" >&2
    return 1
  fi

  while getopts "s" opt; do
    echo $opt # This line is here to test how many times we go through the loop
    case $opt in
      s) 
        squash=true
        shift
        ;;
      *) 
        ;;
    esac
  done
}

The getch -s master case is where the strangeness happens. The above should spit out s once, but instead, I get this:

[user@host:git-repositories/temp]$ getch -s master
s
s
[user@host:git-repositories/temp]$

Why is it parsing the -s opt twice?

© Stack Overflow or respective owner

Related posts about bash

Related posts about function