Compare commits

...

2 Commits

  1. 33
      teil23/parseargs.sh

33
teil23/parseargs.sh

@ -1,17 +1,20 @@
#!/bin/bash #!/bin/bash
display_help() {
echo "Usage: ${0} [options]"
echo "Options:"
echo " -h, --help Show this help message"
echo " -v, --verbose Enable verbose mode"
echo " -f, --file <file> Specify a file"
echo " -n, --number <num> Specify a number (default: 42)"
}
# Universelle Parameterparser-Funktion # Universelle Parameterparser-Funktion
parse_args() { parse_args() {
POSITIONAL=() POSITIONAL=()
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
case "$1" in case "${1}" in
-h|--help) -h|--help)
echo "Usage: $0 [options]" display_help
echo "Options:"
echo " -h, --help Show this help message"
echo " -v, --verbose Enable verbose mode"
echo " -f, --file <file> Specify a file"
echo " -n, --number <num> Specify a number (default: 42)"
exit 0 exit 0
;; ;;
-v|--verbose) -v|--verbose)
@ -19,7 +22,7 @@ parse_args() {
shift shift
;; ;;
-f|--file) -f|--file)
if [[ -z "$2" || "$2" == -* ]]; then if [[ -z "${2}" || "${2}" == -* ]]; then
echo "Error: --file requires a non-empty argument." echo "Error: --file requires a non-empty argument."
exit 1 exit 1
fi fi
@ -27,11 +30,11 @@ parse_args() {
shift 2 shift 2
;; ;;
-n|--number) -n|--number)
if [[ -z "$2" || "$2" == -* ]]; then if [[ -z "${2}" || "${2}" == -* ]]; then
echo "Error: --number requires a non-empty argument." echo "Error: --number requires a non-empty argument."
exit 1 exit 1
fi fi
NUMBER="$2" NUMBER="${2}"
shift 2 shift 2
;; ;;
--) # Explicit end of options --) # Explicit end of options
@ -54,13 +57,3 @@ parse_args() {
VERBOSE="${VERBOSE:-false}" VERBOSE="${VERBOSE:-false}"
NUMBER="${NUMBER:-42}" NUMBER="${NUMBER:-42}"
} }
# Aufruf der Funktion mit allen Skriptargumenten
parse_args "$@"
# Beispielnutzung
echo "Verbose mode: $VERBOSE"
echo "File: ${FILE:-<not set>}"
echo "Number: $NUMBER"
echo "Positional arguments: $@"

Loading…
Cancel
Save