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; 
case $opt in
    h ) {
            echo "help!!!"
            exit 1
    } ;;

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 ;;
  • 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

getopts cannot handle long arguments:

$ ( set -- --help ; while getopts -- -help opt; do echo "$opt"; done )

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.

  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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