0

I have a bash function with an option to print lines warning messages in red colour using tput. For the warning, I would like to use either just -w (everything gets printed in red) 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
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.