I have this read operation:

read -p "Please enter your name:" username

How could I verify the users name, in one line?

If it's not possible in a sane way in one line, maybe a Bash function putted inside a variable is a decent solution?

Name is just an example, it could be a password or any other common form value.

Verifying means here: Requesting the user to insert the name twice and to ensure the two values are the same.


That the user typed (or, possibly, copied and pasted...) the same thing twice is usually done with two read calls, two variables, and a comparison.

read -p "Please enter foo" bar1
read -p "Please enter foo again" bar2
if [ "$bar1" != "$bar2" ]; then
   echo >&2 "foos did not match"
   exit 1

This could instead be done with a while loop and condition variable that repeats the prompts-and-checks until a match is made, or possibly abstracted into a function call if there are going to be a lot of prompts for input.

  • I assume that if I want to use this code in various other scripts, I could put the if statement and its variable in a file, source that file, and then use the two read operations on another file. Is that correct? – user9303970 Feb 5 '18 at 8:26
  • for multiple usages a function would be more appropriate – thrig Feb 5 '18 at 15:10

To expand on thrig's answer and include the function you had requested:


enter_thing () {
    unset matched
    while [[ -z "$matched" ]]; do
        read -rp "Please enter $@: " thing1
        read -rp "Please re-enter $@: " thing2
        if [[ "$thing1" == "$thing2" ]]; then
            echo "Error! Input does not match" >&2
    echo "$thing2"

In a script you could call it like:

username=$(enter_thing "name")
email=$(enter_thing "email")
password=$(enter_thing "password")
  • Thx, I thumbed up. – user9303970 Feb 5 '18 at 8:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.