Linux command
read 命令
文本
复制后可按需替换文件名、目录或参数。
常用示例
Read a line
read [variable]
Read with a custom prompt
read -p "Enter your name: " [name]
Read silently
read -s -p "Password: " [password]
Read with a timeout
read -t 5 [variable]
Read a single character
read -n 1 [char]
Read into an array
read -a [array]
Read from a file
while read line; do echo "$line"; done < [file]
说明
read is a shell builtin that reads a line from standard input (or a file descriptor) and splits it into words, assigning them to variables. It is fundamental to interactive shell scripts and processing text files. Without variable names, input is stored in the REPLY variable. With multiple variables, words are assigned in order, with remaining words going to the last variable. Words are split according to the IFS (Internal Field Separator) variable. The -r option is recommended for most uses as it prevents backslash interpretation, which can cause unexpected behavior with file paths or special characters. In while read loops, read returns false (exit status 1) at end-of-file, making it ideal for processing files line by line.
参数
- -p _prompt_
- Display prompt string before reading (bash)
- -s
- Silent mode; do not echo input (for passwords)
- -t _timeout_
- Timeout after specified seconds; fail if no input
- -n _nchars_
- Return after reading specified number of characters
- -N _nchars_
- Read exactly N characters, ignoring delimiters
- -a _array_
- Read words into array variable
- -d _delim_
- Use specified delimiter instead of newline
- -r
- Do not treat backslash as escape character (raw mode)
- -u _fd_
- Read from file descriptor instead of stdin
- -e
- Use readline for input (enables line editing)
FAQ
What is the read command used for?
read is a shell builtin that reads a line from standard input (or a file descriptor) and splits it into words, assigning them to variables. It is fundamental to interactive shell scripts and processing text files. Without variable names, input is stored in the REPLY variable. With multiple variables, words are assigned in order, with remaining words going to the last variable. Words are split according to the IFS (Internal Field Separator) variable. The -r option is recommended for most uses as it prevents backslash interpretation, which can cause unexpected behavior with file paths or special characters. In while read loops, read returns false (exit status 1) at end-of-file, making it ideal for processing files line by line.
How do I run a basic read example?
Run `read [variable]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does -p _prompt_ do in read?
Display prompt string before reading (bash)