Reading and Validating Prompted Input in Bash

Here’s how to create a readvalid Bash procedure that will print a prompt the user to input something from the terminal command line and show them an optional default value. If there is a default value then entering with no input will cause the default value to be used. Otherwise, it will loop forever waiting on valid input.

But First …

You really need to have a solid handle on Bash scripting and regular expressions before this will make much sense.

Step by Step

Create a function like the following in your .bashrc or script.

readvalid () {
  local regx="$1"
  local default="$2"
  local prompt="$3"
  local input=""
  while true; do
    read -p "$prompt" input
    if [[ -n "$input" ]]; then
      if [[ "$input" =~ $regx ]]; then
      [[ -n "$default" ]] && input="$default" && break
  echo "$input"

Here’s how I use it to prompt for a valid SkilStak ID when creating new registrations:

_register () {
  local defID=$(printf "sk%0x%0x%0x" $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256)))
  local id=$(readvalid '^sk[0-9a-f]{6}$' $defID \
    "$(sol y)ID $(sol b1)($(sol c)$defID$(sol b1))$(sol y): $(sol b3) ")
  echo $id
  # do other stuff with it