#=== FUNCTION ================================================================ # NAME: read_value # DESCRIPTION: Read a value from STDIN and handle errors. # PARAMETERS: 1 - Prompt string for the read # 2 - Name of variable to receive the result # 3 - Default value (optional) # RETURNS: 1 on error, otherwise 0 #=============================================================================== read_value () { local prompt="${1:?Usage: read_value prompt outputname [default]}" local outputname="${2:?Usage: read_value prompt outputname [default]}" local default="${3:-}" local var if [[ $default != "" ]]; then default="-i \"$default\"" fi # # Read (with eval to ensure everything's substituted properly) # eval "read -e $default -p '$prompt' var" res="$?" if [[ $res -ne 0 ]]; then echo "Read aborted" return 1 fi # # Return the value in the nominated variable # var="${var//\"/}" eval "$outputname=\"$var\"" return 0 } #=== FUNCTION ================================================================ # NAME: check_value # DESCRIPTION: Checks a value against a list of regular expressions # PARAMETERS: 1 - the value to be checked # 2..n - valid regular expressions # RETURNS: 0 if the value checks, otherwise 1 #=============================================================================== check_value () { local value="${1:?Usage: check_value value [list_of_regex]}" local matches=0 # # Drop parameter 1 then there should be more # shift if [[ $# == 0 ]]; then echo "Usage: check_value value [list_of_regex]" return 1 fi # # Loop through the regex args checking the value, counting matches # while [[ $# -ge 1 ]] do if [[ $value =~ $1 ]]; then (( matches++ )) fi shift done # # No matches, then the value is bad # if [[ $matches == 0 ]]; then return 1 else return 0 fi } #=== FUNCTION ================================================================ # NAME: read_and_check # DESCRIPTION: Reads a value (see read_value) and checks it (see check_value) # against an arbitrary long list of Bash regular expressions # PARAMETERS: 1 - Prompt string for the read # 2 - Name of variable to receive the result # 3 - Default value (optional) # 4..n - Valid regular expressions # RETURNS: Nothing #=============================================================================== read_and_check () { local prompt="${1:?Usage: read_and_check prompt outputname [default]}" local outputname="${2:?Usage: read_and_check prompt outputname [default]}" local default="${3:-}" read_value "$prompt" "$outputname" "$default" shift 3 until check_value "${!outputname}" $* do echo "Invalid input: ${!outputname}" read_value "$prompt" "$outputname" "$default" done return }