getopts-long-template.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/bin/bash
  2. set -euo pipefail
  3. # Klimbim Software collection, A bag full of things
  4. # Copyright (C) 2011-2023 Johannes 'Banana' Keßler
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. # 2023 http://www.bananas-playground.net
  19. # getopts long example and template
  20. # more detail can be found here https://www.shellscript.sh/examples/getopt/
  21. Help() {
  22. echo
  23. echo "Syntax: `basename "$0"` -n [-h|v|V]"
  24. echo "Available ptions are:"
  25. echo "-n | --name Input your name."
  26. echo "[-h | --help Print this Help and exit.]"
  27. echo "[-v | --verbose Verbose mode.]"
  28. echo "[-V | --version Print software version and exit.]"
  29. echo
  30. }
  31. VERBOSE="false"
  32. NAME=""
  33. VALID_ARGS=$(getopt -o 'vVhn:' --long verbose,version,help,name: -- "$@")
  34. if [[ $? -ne 0 ]]; then
  35. exit 1;
  36. fi
  37. eval set -- "$VALID_ARGS"
  38. while [ : ]; do
  39. case "$1" in
  40. -n | --name)
  41. NAME="$2"
  42. shift 2
  43. ;;
  44. -v | --verbose)
  45. VERBOSE="true"
  46. shift
  47. ;;
  48. -V | --version)
  49. echo "Version 1.0"
  50. shift
  51. exit ;;
  52. -h | --help)
  53. Help
  54. exit 0
  55. ;;
  56. --) shift
  57. break
  58. ;;
  59. *) echo "Unexpected option: $1"
  60. Help
  61. exit
  62. ;;
  63. esac
  64. done
  65. shift "$(($OPTIND -1))"
  66. if [[ -z "$NAME" ]] ; then
  67. echo 'Missing option -n | --name' >&2
  68. exit 1
  69. fi
  70. if [[ "${VERBOSE}" == "true" ]] ; then
  71. echo "DEBUG: Provided ${NAME} for option n"
  72. fi
  73. echo "Your are: ${NAME}"