Input Redirection

Just as you can redirect output, you can redirect input. Instead of typing, feed a file to a command.

Basic Input Redirection

Terminal
$wc -l < file.txt
42
$sort < unsorted.txt
(sorted content)

The command reads from the file instead of keyboard.

Input Redirection vs Filename Argument

These often do the same thing:

Terminal
$wc -l file.txt
42 file.txt
$wc -l < file.txt
42

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:

hljs bash
cat << EOF
This is line 1
This is line 2
This is line 3
EOF
Terminal
$cat << EOF line 1 line 2 EOF
line 1 line 2

EOF is the delimiter (you can use any word).

Creating Config Files

Here documents are great for creating config files in scripts:

hljs bash
cat << EOF > config.json
{
  "port": 3000,
  "debug": true
}
EOF

Here Strings

For a single line:

Terminal
$cat <<< 'hello world'
hello world
$wc -w <<< 'one two three'
3

Shorter than echo 'text' |.

Combining Input and Output

Terminal
$sort < unsorted.txt > sorted.txt

Read from one file, write to another.

Real-World Examples

Send Email Content

hljs bash
mail -s "Report" user@example.com < report.txt

Database Import

hljs bash
mysql database < dump.sql

Feed Script to Interpreter

hljs bash
python3 << EOF
print("Hello from here doc")
print(2 + 2)
EOF

Interactive Programs

Some programs expect interactive input. Here docs can automate them:

hljs bash
ftp << EOF
open server.com
user anonymous
get file.txt
quit
EOF
Knowledge Check

What does the command `sort < data.txt > sorted.txt` do?

Quick Reference

SyntaxEffect
< fileUse file as stdin
<< DELIMHere document (multiple lines)
<<< stringHere string (single string)

Key Takeaways

  • < file reads 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.