Advanced
Searching inSummaries
How to search
  • Words find lesson titles, text and code. Filter by type (guides, courses, programs, books) or stay in this book.
  • book:rhcsa and ch:8 narrow the search; #code finds a word only in commands of the lessons.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Chapter 28Name in the book: Reading Keyboard Input

Read keyboard input

Up to now the scripts only talk. With read they also listen: the user can type values, answer questions and choose from a menu. This chapter covers read and its options, the IFS variable, why you cannot pipe into read, how to check input, and how to build a menu.

  • 8 Lessons
  • 2 Commands
  • 1 Labs

$ run as a normal user# run as root (or with sudo)

Skills in this chapter

  • Read and check user input, build menus

28.1

Read a value with read

read reads one line from stdin into one or more variables. Without a name the line goes into REPLY.

read-integer
#!/bin/bash
 
# read-integer: evaluate the value of an integer.
 
echo -n "Please enter an integer -> "
read int
 
if [[ "$int" =~ ^-?[0-9]+$ ]]; then
    if ((int == 0)); then
        echo "$int is zero."
    elif ((int < 0)); then
        echo "$int is negative."
    else
        echo "$int is positive."
    fi
else
    echo "Input value is not an integer." >&2
    exit 1
fi

28.2

Read several values

With several names, read splits the line into words. The last variable gets the rest of the line.

read var1 var2 var3 var4 var5
a b c d e f g
echo "$var5"
e f g
read var1 var2
a
echo "[$var2]"
[]
read
hello there
echo "$REPLY"
hello there

28.3

Use the read options

Options add a prompt, a time limit, hidden input and more.

OptionWhat it does
-p promptShow a prompt
-sSilent: do not show what is typed (passwords)
-t secondsGive up after a time; exit status not 0
-n numRead only num characters
-rRaw: a backslash is a normal character
-a arrayPut the words into an array
-eUse Readline (editing keys, completion)
-i textDefault text (with -e)
-d charStop at char instead of a new line
-u fdRead from file descriptor fd
read -p "Enter one or more values > "
read -s -p "Password: " pass; echo
read -t 10 -p "Answer in 10 seconds > " ans || echo "Too slow"
read -e -p "Folder: " -i "$HOME" dir
read -n 1 -p "Continue? (y/n) " key

Remember

Use read -r in scripts that read file lines. Without -r, backslashes in the data are changed.

28.4

Split input with IFS

IFS (Internal Field Separator) decides where read splits words. The default is space, tab and new line.

read-ifs
#!/bin/bash
 
# read-ifs: read fields from a file
 
FILE=/etc/passwd
 
read -p "Enter a username > " user_name
 
file_info="$(grep "^$user_name:" "$FILE")"
 
if [ -n "$file_info" ]; then
    IFS=":" read user pw uid gid name home shell <<< "$file_info"
    echo "User =      '$user'"
    echo "UID =       '$uid'"
    echo "GID =       '$gid'"
    echo "Full Name = '$name'"
    echo "Home Dir. = '$home'"
    echo "Shell =     '$shell'"
else
    echo "No such user '$user_name'" >&2
    exit 1
fi
  • IFS=":" read … changes IFS only for this one read command.
  • <<< is a here string: the text becomes the stdin of the command.

Commands in this lesson

28.5

Know why you cannot pipe into read

echo "foo" | read x seems to work but x stays empty. Each part of a pipeline runs in a subshell, and the subshell's variables are lost when it ends.

echo "foo" | read x
echo "[$x]"
[]
read x <<< "foo"
echo "[$x]"
[foo]

At work

Use a here string (<<<), a here document, or process substitution (read x < <(command)) instead of a pipe. More in Exotica: advanced tricks.

28.6

Check the input

A good script expects bad input: empty lines, letters instead of numbers, many words. Test every value before you use it.

read-validate
#!/bin/bash
 
invalid_input () {
    echo "Invalid input '$REPLY'" >&2
    exit 1
}
 
read -p "Enter a single item > "
 
# input is empty (invalid)
[[ -z "$REPLY" ]] && invalid_input
 
# input is multiple items (invalid)
(( "$(echo "$REPLY" | wc -w)" > 1 )) && invalid_input
 
# is input a valid filename?
if [[ "$REPLY" =~ ^[-[:alnum:]\._]+$ ]]; then
    echo "'$REPLY' is a valid filename."
    if [[ -e "$REPLY" ]]; then
        echo "And file '$REPLY' exists."
    else
        echo "However, file '$REPLY' does not exist."
    fi
else
    echo "The string '$REPLY' is not a valid filename."
fi

28.8

Summary of the chapter

read gets input; -p, -s, -t, -r help; IFS splits; never pipe into read; always validate.

1Which command asks for a password without showing it?
2Why is x empty after echo foo | read x?

read runs in a subshell of the pipeline; its variable is lost when the subshell ends.

3How do you split /etc/passwd lines at : with read?

IFS=":" read user pw uid gid name home shell <<< "$line".

Practice

All commands in this chapter