read
The read
command in Unix-like operating systems is used in shell scripting to take input from the user or from a file. It is a simple but powerful tool for making scripts interactive or for processing input data line by line.
Basic Syntax
variable: The name of the variable that will store the input.
options: Various flags that modify the behavior of the
read
command.
Examples
Reading User Input
Reading Multiple Variables
Reading Input with a Prompt
You can use the -p
option to display a prompt without using echo
:
Silent Input (e.g., Passwords)
The -s
option hides the input, useful for passwords:
Reading Input from a File
You can use the read
command to process a file line by line:
Advanced Examples
Reading Input with a Timeout
The -t
option sets a timeout for input:
Reading a Single Character
The -n
option reads a specified number of characters (usually one):
Reading Input with a Delimiter
The -d
option allows specifying a delimiter other than newline:
Reading an Array
Using Default Values
You can provide a default value if the user input is empty:
Practical Use Cases
Menu Selection
Confirmation Prompt
Conclusion
The read
command is a versatile and essential tool for shell scripting, enabling scripts to interact with users or process input data effectively. By understanding its various options and use cases, you can create more dynamic and responsive scripts.
Last updated