-   Programming (
-   -   Passing command line arguments through getopts and long options (

neville310 04-15-2007 02: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.


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

eval set -- "$GETOPT"

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

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

cfaj 04-16-2007 12:02 AM


Originally Posted by neville310

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 02:51 AM

yes you must remember

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

zaichik 04-16-2007 06: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 10:45 AM.