function-template.sh 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # This is my bash function template.
  2. #
  3. # Usage:
  4. # source THISFILE
  5. # example # print help
  6. # example --help # print help
  7. # example foo # run with one arg
  8. # example foo bar # run with two args
  9. #
  10. #
  11. source $HOME/lib/bash/bashutils.sh # error,warning,...
  12. ARGV=("$@")
  13. ARGC=("$#")
  14. function example() ( # function in subshell, own namespece.
  15. ARG1="${1:-NONE}"
  16. ARG2="${2:-NONE}"
  17. function usage () {
  18. message=${1:-""}
  19. cat <<EOF 1>&2
  20. Usage: $0 [options] ARG1 [ARG2]
  21. EXAMPLE does this..
  22. -h| --help print help text
  23. ARG1 This argument (required) does..
  24. ARG2 This argument (optional) does...
  25. Examples:
  26. example thing1
  27. example thing1 thing2
  28. example --help
  29. EOF
  30. if [[ "${message}" != "" ]]; then
  31. echo 2>&1
  32. error "${message}"
  33. fi
  34. }
  35. case $ARG1 in
  36. NONE) usage "Missing ARG1" && return 1;;
  37. -d|--debug) DEBUG=1 && shift;;
  38. -h|--help) usage && return 1;;
  39. esac
  40. if [ "$ARG2" == "NONE" ]; then
  41. info "ARG2 not defined"
  42. else
  43. echo # do something with ARG2
  44. fi
  45. cmd="echo $ARG1 $ARG2"
  46. debug "command: ${cmd}" # export DEBUG=1 for debugging
  47. [[ -v DEBUG ]] && set -x
  48. echo args are $* || warn "something went wrong"
  49. )