views:

75

answers:

3

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?

+1  A: 

I can't reproduce the problem either, on an Ubuntu 10.4 box running Bash 4, or my MacOSX box running Bash 3.2.17.

Your shell environment might be tainted by earlier debugging efforts.

Have you tried to start with a new terminal window? Or start a new shell with 'exec bash' and try the function again.

stefanl@ubuntu:~ $ 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
> }
stefanl@ubuntu:~ $ getch -s master
s
Stefan Lasiewski
I tried doing a new subshell, as you suggested, and it worked. Must have done something to my environment beforehand... Anyway, thanks for helping!
ABach
This happens from time to time. It's easy to become stuck debugging a script, and forget that your environment can become corrupt.
Stefan Lasiewski
A: 

Try parsing the options outside of a function you've written. I toyed around with this a little bit more this afternoon. I had a hard time having it work properly when parsing the options in a function as opposed to just in the main body of the script.

Otherwise, I don't really know what to tell you.

Precision
+1  A: 

Here's a way to do it without getopts:

http://bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html

yabt
Thanks for the link!
ABach