change-time: Complete input with Enter, allow Backspace, don't require leading zeroes

Allow Backspace in input.  It's really frustrating otherwise if a typo
cannot be corrected, and worse, the backspace key actually produces a
character that becomes part of the input.

Complete input with Enter.  It is surprising when the script just
moves on right away once a fourth/second digit is entered, and worse,
users expecting to press Enter could reasonably press it before
realizing the script did not require it, which then skips the _next_
prompt inadvertently.  Users with imperfect typing might double a
digit unintentionally, do not force them to proceed with an incorrect
value.

Removing '-n $digits' from read does both of those.  Add '-r' so
backslashes do not have unexpected behavior.

Don't require leading zeroes, zero-pad automatically.

Signed-off-by: Jonathon Hall <jonathon.hall@puri.sm>
This commit is contained in:
Jonathon Hall 2024-08-06 09:12:03 -04:00
parent 16f0793648
commit 770815cba8
No known key found for this signature in database
GPG Key ID: 1E9C3CA91AE25114

View File

@ -14,23 +14,26 @@ get_date () {
max="$3"
digits="$4"
echo -e -n "Please insert $field_name (between $min-$max) (Enter key to accept $min)\n"
read -n $digits value
read -r value
echo -e "\n"
#if enter
if [[ $value = "" ]]; then
value=$min
fi
#must be a $4 digits number between $2 and $3
while [[ ! $value =~ ^[0-9]{$digits} ]] || [[ ${value#0} -lt $min ]] || [[ ${value#0} -gt $max ]];
#must be a number between $2 and $3
while [[ ! $value =~ ^[0-9]*$ ]] || [[ ${value#0} -lt $min ]] || [[ ${value#0} -gt $max ]];
do
echo -e -n "$field_name is wrong: you entered \"$value\". Please try again, it must be $digits digits number between $min and $max (press Enter to accept $min) \n"
read -n $digits value
echo -e -n "$field_name is wrong: you entered \"$value\". Please try again, it must be a number between $min and $max (press Enter to accept $min) \n"
read -r value
echo -e "\n"
if [[ $value = "" ]]; then
value=$min
fi
done
# Pad with zeroes to digits
value="$(printf "%0${digits}u" "$value")"
}
get_date "year" "2024" "2200" "4"