JA1
JA1

Reputation: 568

Prompt if answer is correct then validate in Bash

This is the initial script that is executed during the beginning of the install. It will capture the user input then write it to the another bash script where the variables are called. It works great as is however, I would like to add in a confirmation for each question.

After the user enters the email for example I would like for it to echo back what they typed to confirm it is correct with a yes or no. If yes then write it to the other script and move on to the next question. If not loop back to the beginning of the statement so they can correct the answer. Once completed I would like to echo out the results.

If someone can provide some pointers that would be great. I was looking at these examples In Bash, how to add "Are you sure [Y/n]" to any command or alias?

#!/bin/bash
read -p "Who is the primary Email recipient? : " TO
    echo "TO=$TO" >> /var/tmp/ProcMon
read -p "What is the server hostname : " FROM
    echo "FROM=$FROM" >> /var/tmp/ProcMon

Upvotes: 0

Views: 380

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

function prompt_and_confirm {
    local var=$1
    local prompt=$2
    local value
    local -u ans

    while :; do
        read -p "$prompt" value
        read -p "You entered: '$value': confirm [y/n] " ans
        [[ ${ans:0:1} == "Y" ]] && break
    done
    echo "$var=$value"
}

prompt_and_confirm TO   "Who is the primary Email recipient? : " >> /var/tmp/ProcMon
prompt_and_confirm FROM "What is the server hostname? : "        >> /var/tmp/ProcMon

Notes:

Upvotes: 3

Related Questions