0

I try to achieve a script with multi options. I started with the doc, get some errors, went to the browser. Read some links and find this on SO : Using getopts in bash shell script to get long and short command line options.

So I read it and rewrote my script. I made a mistake somewhere. Where am I wrong ?

SH

#!/bin/sh

TEMP=`getopt -o vfts: --long verbose,format,type,style: \
             -n 'opt2' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

VERBOSE=false
FORMAT=
TYPE=
STYLE=
while true; do
    case "$1" in
        -v | --verbose ) VERBOSE=true; shift ;;
        -f | --format ) FORMAT="$2"; shift 2 ;;
        -t | --type ) TYPE="$2"; shift 2 ;;
        -s | --style ) STYLE="$2"; shift 2 ;;
        -- ) shift; break ;;
        -*) break ;;
        * ) break ;;
    esac
done

echo "verbose = $VERBOSE"
echo "format = $FORMAT"
echo "type = $TYPE"
echo "style = $STYLE"

Output

> ./opt2.sh -v -f fofo -t toto -s soso

verbose = true // ok
format = -t // should be fofo
type =  // should be toto
style = soso // ok
Community
  • 1
  • 1
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • run your script `sh -x ./opt2.sh .....` – KevinDTimm Mar 17 '14 at 15:35
  • not if I use a chmod +x on opt2.sh. – aloisdg Mar 17 '14 at 15:39
  • @aloisdg the `-x` that Kevin referred to does not mean execute, it sets the xtrace shell option which will cause each statement executed by the shell script to be printed to the console. In that way you can see where your script is going wrong. – wich Mar 17 '14 at 16:01

2 Answers2

4

Your options string is wrong, it should be vf:t:s:. The colon indicates a required argument which each of your options except for v has. Also need to adjust your long options string accordingly.

wich
  • 16,709
  • 6
  • 47
  • 72
2

You could have done some debugging yourself, quite easily:

$ set -- -v -f fofo -t toto -s soso
$ TEMP=$(getopt -o vfts: --long verbose,format,type,style: -- "$@")
$ echo "$TEMP"
 -v -f -t -s 'soso' -- 'fofo' 'toto'

Hmm, your -f and -t arguments are disconnected. Make them required

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:,type:,style: -- "$@")
$ echo "$TEMP"
 -v -f 'fofo' -t 'toto' -s 'soso' --

To demonstrate that the commas apparently are not strictly required in the --long definition:

$ TEMP=$(getopt -o vf:t:s: --long verbose,format:type:style: -- "$@")
$ echo $?; echo "$TEMP"
0
 -v -f 'fofo' -t 'toto' -s 'soso' --
glenn jackman
  • 238,783
  • 38
  • 220
  • 352