Monday, September 10, 2012

bash option processing part 2: getopt()

Just when you thought there was one safe choice to make for bash arg processing...   :-)

Bash getopts command - Stack Overflow:

I am following IBM's example from their website:
#!/bin/bash
echo "OPTIND starts at $OPTIND"
while getopts ":pq:" optname
  do
    case "$optname" in
      "p")
        echo "Option $optname is specified"
        ;;
      "q")
        echo "Option $optname has value $OPTARG"
        ;;
      "?")
        echo "Unknown option $OPTARG"
        ;;
      ":")
        echo "No argument value for option $OPTARG"
        ;;
      *)
      # Should not occur
        echo "Unknown error while processing options"
        ;;
    esac
    echo "OPTIND is now $OPTIND"
  done
All I want to to is have an option whose name is more than 1 letter. ie -pppp and -qqqq instead of -p and -q.
I have written my program and implementing -help is giving me a problem...
share|edit


Upfloor's are right. the getopt utility support long options while you can use --option. Maybe you can try this.
#!/bin/bash
args=`getopt -l help :pq: $*`
for i in $args; do
    case $i in
    -p) echo "-p"
        ;;
    -q) shift;
        optarg=$1;
        echo "-q $optarg"
        ;;
    --help)
        echo "--help"
        ;;
    esac
done
share|edit

'via Blog this'

No comments:

Post a Comment