1

I created a bash script where I would like to add a help options like -h, --help, --verbose and some others.

If I create it like described here Will this be a standard solution?

# Execute getopt on the arguments passed to this program, identified by the special character $@
PARSED_OPTIONS=$(getopt -n "$0"  -o h123: --long "help,one,two,three:"  -- "$@")

#Bad arguments, something has gone wrong with the getopt command.
if [ $? -ne 0 ];
then
  exit 1
fi

# A little magic, necessary when using getopt.
eval set -- "$PARSED_OPTIONS"


# Now goes through all the options with a case and using shift to analyse 1 argument at a time.
#$1 identifies the first argument, and when we use shift we discard the first argument, so $2 becomes $1 and goes again through the case.
while true;
do
  case "$1" in

    -h|--help)
      echo "usage $0 -h -1 -2 -3 or $0 --help --one --two --three"
     shift;;

    -1|--one)
      echo "One"
      shift;;

    -2|--two)
      echo "Dos"
      shift;;

    -3|--three)
      echo "Tre"

      # We need to take the option of the argument "three"
      if [ -n "$2" ];
      then
        echo "Argument: $2"
      fi
      shift 2;;

    --)
      shift
      break;;
  esac
done

Or is there another defined way how to implement this?

rubo77
  • 28,966

1 Answers1

1

It is actually quite common for shell scripters to write their own argument parsing using a case statement in a very similar fashion as you. Now, whether or not it is the best or most standard solution, that's up for debate. Personally, because of my experience with C, I prefer to use a utility called getopt.

From the getopt.1 man page:

getopt is used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. It uses the GNU getopt(3) routines to do this.

Given that you're already calling getopt, I would say you are on exactly the right track. If you wanted to, you could simply iterate over the command line arguments with a case statement to handle the cases; but, as you have probably already discovered, getopt actually does all this heavy lifting for you.


TL;DR: It's a shell script, you get to implement it how you want; but getopt is a great utility for this.

HalosGhost
  • 4,790
  • thanks for the info, I used it now and this is my result: https://github.com/rubo77/mouse-speed – rubo77 Jul 04 '14 at 17:44