Posted By

syladmin on 12/19/09


Tagged

Bash vim parsing documenting


Versions (?)

display embeded comments for every --opt, usefull for auto documenting your script


 / Published in: Bash
 

  1. #!/bin/bash
  2.  
  3. # print the text embedded in the case that parse options from command line.
  4. # the block is matched with the marker 'CommandParse' in comment, until 'esac'
  5. extract_cmdl_options()
  6. {
  7. # use vim for parsing:
  8. # 1st grep the case block and copy in register @p + unindent in the buffer of the file itself
  9. # 2nd filter lines which start with --opt or +opt and keep comment on hte following lines until an empty line
  10. # 3rd discard changes in the buffer and quit
  11. vim -n -es -c 'g/# CommandParse/+2,/^\s\+esac/-1 d p | % d | put p | %<' \
  12. -c 'g/^\([-+]\+[^)]\+\))/,/^\(\s\+[^- \t#]\|^$\)/-1 p' \
  13. -c 'q!' $0
  14. }
  15.  
  16.  
  17. # command line parsing {{{
  18. arg_max=15
  19. arg_endarg=0
  20. # --------------------------------------------------
  21. while [ $arg_endarg -eq 0 -a $# -gt 0 -a $arg_max -gt 0 ]
  22. do
  23. arg_max=$(($arg_max - 1))
  24.  
  25. # loop on each argument, if it's in the case modify the associated var
  26. # else end argument parsing and continue to the main routine
  27.  
  28. # CommandeParse:
  29. case "$1" in
  30. --help)
  31. # This help message
  32.  
  33. # print script header + the option desc
  34. # http://www.commandlinefu.com/commands/view/3344/display-an-embeded-help-message-from-bash-script-header
  35. sed -n -e '/^# Usage:/,/^$/ s/^# \?//p' < $0
  36. extract_cmdl_options
  37. exit
  38. ;;
  39. --some_option)
  40. echo "do something undocumented"
  41. ;;
  42. --etc)
  43. # nothing done
  44. ;;
  45. --exemple)
  46. # print more example, and exit
  47. cat /etc/motd
  48. exit
  49. ;;
  50. *)
  51. # stop parsing
  52. arg_endarg=1
  53. ;;
  54. esac
  55. if [ $arg_endarg -eq 0 ]
  56. then
  57. shift
  58. fi
  59. done
  60. # DONE parsing argument }}}

Report this snippet  

You need to login to post a comment.