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
Read a value with read
read reads one line from stdin into one or more variables. Without a name the line goes into REPLY.
#!/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
fiRead several values
With several names, read splits the line into words. The last variable gets the rest of the line.
Use the read options
Options add a prompt, a time limit, hidden input and more.
| Option | What it does |
|---|---|
-p prompt | Show a prompt |
-s | Silent: do not show what is typed (passwords) |
-t seconds | Give up after a time; exit status not 0 |
-n num | Read only num characters |
-r | Raw: a backslash is a normal character |
-a array | Put the words into an array |
-e | Use Readline (editing keys, completion) |
-i text | Default text (with -e) |
-d char | Stop at char instead of a new line |
-u fd | Read 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) " keyOnthoud
Use read -r in scripts that read file lines. Without -r, backslashes in the data are changed.
Split input with IFS
IFS (Internal Field Separator) decides where read splits words. The default is space, tab and new line.
#!/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
fiIFS=":" read …changesIFSonly for this onereadcommand.<<<is a here string: the text becomes the stdin of the command.
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.
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.
Check the input
A good script expects bad input: empty lines, letters instead of numbers, many words. Test every value before you use it.
#!/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."
fiSummary 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".