Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have created a script which takes parameters and arguments. I want to insert the --help argument.

I already know how to parse normal arguments with -, but I don't know how to parse the -- ones.

to parse optiopns for test.sh -h i use the following check

while getopts ":h" opt; 
do 
case $opt in
    h ) {
            echo "help!!!"
            exit 1
    } ;;
esac
done

But I want to have the option to call the script with test.sh --help

Thanks in advance.

P.S. I am using Ubuntu 12.04...but it doesn't really matter.

Apparently I can't answer my own question if I have so less rep. I found the solution in one of the .sh scripts from /usr/bin

  if test $# = 1; then
    case "$1" in
      --help | --hel | --he | --h )
        func_usage; exit 0 ;;
      --version | --versio | --versi | --vers | --ver | --ve | --v )
        func_version; exit 0 ;;
    esac
  fi
share|improve this question
    
For the record the script you found is badly written. For example, the --version partial match could be rewritten just as --v*)(assuming you're okay with --vfoo). –  Chris Down Feb 17 '13 at 2:21
    
Yes, thanks. Didn't really need the version one, but I got the point. –  bioShark Feb 17 '13 at 2:27

1 Answer 1

up vote 0 down vote accepted

getopts cannot handle long arguments:

$ ( set -- --help ; while getopts -- -help opt; do echo "$opt"; done )
-
h
e
l
p

If you want to handle long arguments, you need to write your own parser.

The GNU version of getopt does support parsing long options, but you'd be better off not using it; it's not portable, and it breaks on certain types of arguments. For example, it cannot properly parse arguments with whitespace in them.

share|improve this answer
    
Thanks. I have in the mean time found a solution in one of the shell scripts from /usr/bin :) I've edited the answer in my question –  bioShark Feb 17 '13 at 2:14
    
@bioShark Like I said, if you want to handle long arguments you need to write your own parser -- the script in your question is an example of that. :-) –  Chris Down Feb 17 '13 at 2:18
    
well yes, I know it's a parser :) Anyway, thanks. I'll accept your answer. –  bioShark Feb 17 '13 at 2:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.