function-template.sh 1.4 KB

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