LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Passing command line arguments through getopts and long options (http://www.linuxquestions.org/questions/programming-9/passing-command-line-arguments-through-getopts-and-long-options-546276/)

neville310 04-15-2007 03:40 PM

Passing command line arguments through getopts and long options
 
I am trying to implement getopts into my Bash script for passing command line arguments, yet I am encountering difficulty with the actual syntax and long options support. The man for getopts did not include clear examples, so most examples came from other scripts on the net, which may not have the correct syntax. In addition, several approaches exist leading to more confusion with a proper explanation. Please let know if long options are a possibility with getopts. Long options are options flags like --files or --verbose while shot options are -f or -v.

Code:

GETOPT=$(getopts -o fdp:uvh -n ${SCRIPTNAME} -- "$@")
if [ $? -ne 0 ]; then
  usage
fi

eval set -- "$GETOPT"


while [ "$1" != "" ]; do
    case "$1" in
        -f | --files )          FLAG_FILES="true"
                                ;;
        -d | --directories )    FLAG_DIR="true"
                                ;;
        -p | --preset )          shift
                                PRESET=$1
                                ;;
        -u | --undo )            FLAG_UNDO="true"
                                ;;
        -v | --verbose )        VERBOSE="yes"
                                ;;
        -h | --help )            usage
                                exit
                                ;;
        * )                      usage
                                exit 1
    esac
    shift
done



Bash return a /home/neville/bin/Filerenamer.sh: line 103: getopts: -o: invalid option. Please lead me to a syntax that support long options.

cfaj 04-16-2007 01:02 AM

Quote:

Originally Posted by neville310
Code:

GETOPT=$(getopts -o fdp:uvh -n ${SCRIPTNAME} -- "$@")


Shouldn't that be getopt, not getopts?

As for the rest, I don't use getopt, so I don't know what it expects. Try reading the man page.

Get your getopts command correct before worrying about anything else.


bigearsbilly 04-16-2007 03:51 AM

yes you must remember

there is getopt and getopts
they ain't the same thang!

zaichik 04-16-2007 07:38 AM

He did read the man page.

I don't see anything in the getopts man page about support for long options. Here is a script that implements long option support for bash scripts, and here is a script that shows how to implement it. Caveat emptor: I have neither tried these out, nor gone through the code at any length to see how effective they may be.

Give them a try and let us know how they work.


All times are GMT -5. The time now is 12:06 PM.