Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 28Naam in het boek: 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 Lessen
  • 2 Commando's
  • 1 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

Vaardigheden in dit hoofdstuk

  • Invoer lezen en controleren, menu's bouwen

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

Onthoud

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.

Commando's in deze les

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]

Op het werk

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".

Oefenen

Alle commando's in dit hoofdstuk