Home > Mobile >  How can I add formatting punctuation to user input as they type text using Bash's "read&qu
How can I add formatting punctuation to user input as they type text using Bash's "read&qu

Time:11-02

I have the following lines to prompt a user to enter a date/time that I use further down in my script:

printf "Please insert start of time window in format YYYY-MM-DD HH:MM:SS: \n"
read startDatetime

Is there a way I can have the "read" prompt insert in the dashes for the date, the space between the date and time, and the colons for the time dynamically as a user types? I know this is possible using JavaScript on the web, but I am specifically looking for a command line version of that functionality.

I searched the web for an answer to this and cannot find one. I see an option for delimiter in the read Man Page but cannot see how it would achieve what I am trying to do.

CodePudding user response:

You can cobble it together by limiting the number of characters you read at a time using the -N flag for read:

echo "Please enter start time in YYYY-MM-DD HH:MM:SS format"
read -rN4 year
printf '-'
read -rN2 month
printf '-'
read -rN2 day
printf ' '
read -rN2 hour
printf ':'
read -rN2 minute
printf ':'
read -rN2 second
echo

printf -v datetime '%s-%s-%s %s:%s:%s' \
    "$year" "$month" "$day" "$hour" "$minute" "$second"

echo "You entered $datetime"

Looks like this:

enter image description here


Alternatively, with the option to move the cursor back past the automatically added -, blank, and :: we can use tput to move the cursor, clear the line, and then use read -e (use readline for input) and -i (prefill prompt):

moveup=$(tput cuu1)
clearln=$(tput el)

echo "Please enter start time in YYYY-MM-DD HH:MM:SS format"
read -rN4 datetime
printf '%b' '\r' "$clearln"
read -erN7 -i "$datetime-" datetime
printf '%b' '\r' "$moveup" "$clearln"
read -erN10 -i "$datetime-" datetime
printf '%b' '\r' "$moveup" "$clearln"
read -erN13 -i "$datetime " datetime
printf '%b' '\r' "$moveup" "$clearln"
read -erN16 -i "$datetime:" datetime
printf '%b' '\r' "$moveup" "$clearln"
read -erN19 -i "$datetime:" datetime

echo "You entered $datetime"

This isn't perfect, either: the extra characters are only inserted once, but not when you go back to fix something; and there's a newline inserted after the prompt that results in a blank line, which would be noticeable at the bottom of the terminal emulator:

enter image description here

At this point, you might consider using something like charmbracelet/gum for a very user-friendly interactive input experience at the terminal.

CodePudding user response:

No, it is not possible. But note that read offers the -p switch:

read -p "Please insert start of time window in format YYYY-MM-DD HH:MM:SS: \n" startDatetime
  • Related