help-bash
[Top][All Lists]
Advanced

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

Using optional arguments with getopt


From: lisa-asket
Subject: Using optional arguments with getopt
Date: Fri, 9 Jul 2021 01:31:55 +0200 (CEST)

Have been writing the following bash function to print lines of text. 
Additionally there is an option to print warning messages in red colour using 
tput. 



For the warning, I would like to use either just -w or accept an argument 
value. For instance, using -w 1 will only make the first line red. Am having 
real difficulty implementing this last part.



printf-multiple ()
{
  # Process command line options
  shortopts="hw::"
  longopts="help,warning::"

  opts=$(getopt -o "$shortopts" -l "$longopts" -n "$(basename $0)" -- "$@")
  if [ $? -eq 0 ]; then
    eval "set -- ${opts}"
    while [ $# -gt 0 ]; do
      case "$1" in
        --)
          shift;  break  ;;
        -h|-\?|--help)
          help=1
          printf "Prints two text strings on two lines.\n"
          printf "\$@ TEXT  Sentences to print en new lines.\n"
          shift
          local -r f=0
          break
          ;;
          # ......................................................
        -w|--warning)
          local -r warn=1
          local -r f=1
          shift
          ;;
      esac
    done
  else
    shorthelp=1 # getopt returned (and reported) an error.
  fi

  # ..............................................................

  # set 8-bit 256 colour for warnings
  red=$(tput setaf 9)
  rgl=$(tput sgr0)     # regular foreground
  
  # ..............................................................

  # Brief: Print normal text or warnings
  
  # When `printf` is presented with more arguments than there are
  # format descriptors, the descriptor is repeated as many times as
  # necessary to consume all the arguments.
  if (( f == 1 )); then
    [[ -z warn ]] && printf '%s\n' "$@"
    [[ -n warn ]] && printf '%s\n' ${red}"$@"${rgl}
    
  fi
  return 0
}



reply via email to

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