help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Handling getopt for option without optional argument value


From: lisa-asket
Subject: Handling getopt for option without optional argument value
Date: Fri, 23 Jul 2021 16:22:04 +0200 (CEST)

I have the following bash function but when I call it with

indus-printf-multiple -- "Test" "TNest"

the variable $warn is not being set to 1.

Looks as if I need to introduce `local warn="1"` before `case`.

  ("-w"|"--warning")
     local warn="1"
     case "$2" in


printfm ()
{
  # Process command line options
  shortopts="hVw::"
  longopts="help,version,warning::"

  opts=$(getopt -o "$shortopts" -l "$longopts" -n "${0##*/}" -- "$@")

  if [ $? -ne 0 ]; then
    local shorthelp=1  # getopt returned (and reported) an error.
    return
  fi

  local f=0
  
  if [ $? -eq 0 ]; then
    eval "set -- ${opts}"
    while [ $# -gt 0 ]; do
      case "$1" in
        ("-V"|"--version")
          printf "%s\n" "V01 Jul 2021 Wk27"
          declare -i f=0
          shift
          break
          ;;
        ("-h"|-\?|"--help")
          printf "%s\n" "Print strings."
          declare -i f=0
          shift
          break
          ;;
        # ------------------------------------
        ("-w"|"--warning")
          case "$2" in
            (+([[:digit:]])) 
              local warn="$2"
              shift 2
              ;;
            (*) 
              local warn="1"
              shift 2
              ;;
            esac
            declare -i local f=1
            ;;
          # ----------------------------------------
          (--)
            declare -i local f=1
            shift
            break
            ;;
        esac
      done
    fi

    red=$(tput setaf 9)  
    rgl=$(tput sgr0)
  
    # Print normal text or warnings
  
    if [[ -v $f ]] && (( f != 0 )); then

      # print normal multi-line text
      [[ ! -v $warn ]] && printf '%s\n' "$@"

      # print multi-line warnings

      rge='^[0-9]+$'
      if [[ -v $warn && "$warn" == "1" ]]; then
        printf '%s\n' ${red}"$1"${rgl}  # first line red
        printf '%s\n' "${@:2}"          # remaining, uncoloured
      elif [[ -v $warn && "$warn" =~ $rge ]]; then
        printf '%s\n' ${red}"$@"${rgl}  # all lines red
      fi

    fi
    return 0
  }




reply via email to

[Prev in Thread] Current Thread [Next in Thread]