whiptail

nicolaw 8th April 2018 at 11:38am
Bash CodeSnippets curses dialog TUI

Just a random whiptail example that someone asked me for.

#!/bin/bash

set -euo pipefail

whiptail() {
  command whiptail --fb "$@"
}

msgbox() {
  whiptail \
    --title "${1:-default title}" \
    --msgbox "${2:-default message}" \
    ${3:-10} ${4:-60}
}

inputbox() {
  whiptail \
    --title "${1:-default title}" \
    --inputbox "${2:-default message}" \
    ${4:-10} ${5:-60} "${3:-}" 3>&1 1>&2 2>&3
}

validate_hostname() {
  # Validate characters, starting with a letter, ending in .splunk.
  [[ "${1:-}" =~ ^[a-zA-Z][a-zA-Z0-9\.-]+\.splunk$ ]]
}

main() {
  msgbox "Splunk I.D. Configuration" "The Splunk I.D. will now be configured."

  local hostname="${1:-$(hostname).splunk}"
  local rc=0
  while hostname="$(inputbox \
      "Configure Splunk I.D." \
      "Enter the I.D.  of the splunk server:" "$hostname")" || rc=$?
      ! validate_hostname "$hostname"
  do
    if [[ $rc -ne 0 ]]; then
      >&2 echo "Aborted."
      return $rc
    elif [[ -z "$hostname" ]]; then
      msgbox \
        "Invalid Splunk I.D." \
        "Please enter a valid Splunk I.D."
    else
      msgbox \
        "Invalid Splunk I.D." \
        "Sorry, '$hostname' is not a valid Splunk I.D."
    fi
  done

  msgbox \
    "Thank you." \
    "Your Splunk I.D. of $hostname has been accepted."

  # Do whatever you need to do here.
  #hostname "$hostname"
}

main "$@"

Related