function ask_user_if_empty { # If variable with name $1 is empty, then ask for user input. # # Only one line of user input is allowed. # The input must not be empty. # # arg $1: Name of variable to store user input # arg $2: Text to display (e.g. "Enter hostname:") if [ "$#" -ne 2 ]; then echo 'ask_user_if_empty requires two args!'; return 1 fi for i in "$@"; do if [ -z "${i}" ]; then echo 'ask_user_if_empty: all given args must not be empty'; return 1; fi done local -n ptr=$1 || return $? if [ -z "${ptr}" ]; then # If ptr has no value yet, ask user for input! echo "${2}" read -r ptr || return $? fi # Check string length to be greater than zero! if [ "${#ptr}" -lt 1 ]; then echo 'The input must not be empty!'; return 1; fi } function single_choice_if_empty { # If variable with name $1 is empty, then let user select one of the given options. # # arg $1: Name of variable to store the selected option # arg $2: Text to display # arg $3: Name of variable with array of options to display (for each option there must be two entries in the array: Item and description) if [ "$#" -ne 3 ]; then echo 'single_choice_if_empty requires three args!'; return 1 fi for i in "$@"; do if [ -z "${i}" ]; then echo 'single_choice_if_empty: all given args must not be empty'; return 1; fi done local -n ptr=$1 || return $? if [ -z "${ptr}" ]; then # If ptr has no value yet, ask user for input! local -n MENU_OPTIONS=$3 || return $? ptr=$(dialog --stdout --menu "${2}" 0 0 0 "${MENU_OPTIONS[@]}") || { echo 'Error during menu selection!' exit 1 } clear fi } function multi_choice_if_empty { # If variable with name $1 is empty, then let user select one or more of the given options. # # arg $1: Name of variable to store array of selected options # arg $2: Text to display # arg $3: Name of variable with array of options to display (for each option there must be three entries in the array: Item, description, on/off) if [ "$#" -ne 3 ]; then echo 'multi_choice_if_empty requires three args!'; return 1 fi for i in "$@"; do if [ -z "${i}" ]; then echo 'multi_choice_if_empty: all given args must not be empty'; return 1; fi done local -n ptr=$1 || return $? if [ -z "${ptr}" ]; then # If ptr has no value yet, ask user for input! local -n MENU_OPTIONS=$3 || return $? # shellcheck disable=SC2034 # Variable name used below. TMP1=$(dialog --stdout --checklist "${2}" 0 0 0 "${MENU_OPTIONS[@]}") || { echo 'Error during menu selection!' exit 1 } clear # Result of dialog is a space separated list. # Store this as an array. # Without newline at last array element: https://unix.stackexchange.com/a/519917/315162 # readarray -d " " -t ptr < <(printf '%s' "$TMP1") # space_separated_to_array TMP1 "$1" fi }