Input Redirection
Just as you can redirect output, you can redirect input. Instead of typing, feed a file to a command.
Basic Input Redirection
The command reads from the file instead of keyboard.
Input Redirection vs Filename Argument
These often do the same thing:
Notice the difference:
- With argument: filename is shown
- With redirection: no filename (wc doesn't know where data came from)
Some commands only accept stdin, making input redirection necessary.
Here Documents
Feed multiple lines directly:
cat << EOF
This is line 1
This is line 2
This is line 3
EOF
EOF is the delimiter (you can use any word).
Creating Config Files
Here documents are great for creating config files in scripts:
cat << EOF > config.json
{
"port": 3000,
"debug": true
}
EOF
Here Strings
For a single line:
Shorter than echo 'text' |.
Combining Input and Output
Read from one file, write to another.
Real-World Examples
Send Email Content
mail -s "Report" user@example.com < report.txt
Database Import
mysql database < dump.sql
Feed Script to Interpreter
python3 << EOF
print("Hello from here doc")
print(2 + 2)
EOF
Interactive Programs
Some programs expect interactive input. Here docs can automate them:
ftp << EOF
open server.com
user anonymous
get file.txt
quit
EOF
What does the command `sort < data.txt > sorted.txt` do?
Quick Reference
| Syntax | Effect |
|---|---|
< file | Use file as stdin |
<< DELIM | Here document (multiple lines) |
<<< string | Here string (single string) |
Key Takeaways
< filereads from file instead of keyboard- Here documents (
<< EOF) let you embed multi-line input - Here strings (
<<<) are for single-line input - You can combine
<and>in the same command - Here documents are great for creating files in scripts
Next: the pipe operator - connecting commands.