开发者

Parsing getopts in bash

开发者 https://www.devze.com 2023-01-01 03:36 出处:网络
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 opt

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?


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


Here's a way to do it without getopts:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消