Parse command line arguments and write useful usage message without additional code

41 views Asked by At

This is more a hint than a question: The goal is to parse a command line and create a useful usage message

code:

for arg ; do
  case "$arg" in
    --edit)   # edit file
              cd "$(dirname $0)" && vim "$0"
    ;;
    --noN)    # do NOT create 'NHI1/../tags'
              let noN=1
    ;;
    --noS)    # do NOT create 'HOME/src/*-latest/tags'
              let noS=1
    ;;
    --help)   # write this help message
    ;&
    *)        echo "usage: $(basename $0) options..." 1>&2
              awk '/--?\w+\)/' "$0"  1>&2
              exit
    ;;
  esac
done

This create the usage message:

> build_tags.bash -x
usage: build_tags.bash options...
    --edit)   # edit file
    --noN)    # do NOT create 'NHI1/../tags'
    --noS)    # do NOT create 'HOME/src/*-latest/tags'
    --help)   # write this help message

The clue is that the definition of the case target is also the documentation of the case target.

0

There are 0 answers