Redirecting Input with <
The < operator connects a file to the standard input of a command. Instead of waiting for you to type, or for another command to send data, the command reads its input straight from the file. It is the mirror image of >: where > changes where standard output goes, < changes where standard input comes from.
The Basic Syntax
command < file
The shell opens the file for reading and attaches it to file descriptor 0, standard input, before the command starts. The command then reads from standard input in its usual way and has no idea that a file is on the other end.
The examples in this lesson use two small files:
printf 'pear\napple\nfig\napple\n' > fruits.txt
printf 'alpha beta\ngamma delta\n' > words.txt
How It Works
When Bash sees < fruits.txt it performs these steps:
- It opens
fruits.txtin read-only mode. The file is never modified or emptied. - It makes file descriptor 0 of the new process refer to that open file.
- It starts the command, which reads from standard input.
If the file cannot be opened, the command does not run at all. The file name is removed from the command line before the program starts, so the program does not receive it as an argument.
Argument or Redirection?
For many commands there are two ways to read a file: pass its name as an argument, or redirect it to standard input. Compare them with wc:
wc -l fruits.txt
wc -l < fruits.txt
Output:
4 fruits.txt
4
The count is the same, but the first form prints the file name and the second does not. In the first form, wc receives the name, opens the file itself and can report the name. In the second form, wc only sees an anonymous stream of lines, so it has no name to print. This difference is useful when you want just the number, for example when you store it in a variable:
lines=$(wc -l < fruits.txt)
echo "The file has $lines lines"
Output:
The file has 4 lines
Commands That Only Read Standard Input
Some commands do not take a file name at all and read only standard input. The command tr, which translates or deletes characters, is one of them:
tr 'a-z' 'A-Z' < words.txt
Output:
ALPHA BETA
GAMMA DELTA
Here < is the only way to hand a file to tr, because tr never accepts file names; its arguments are the character sets. Another example removes characters:
tr -d 'aeiou' < words.txt
Output:
lph bt
gmm dlt
The calculator bc reads its expressions from standard input too, so a file of expressions can be fed to it:
echo "2+3" > expr.txt
bc < expr.txt
Output:
5
Using Redirection with sort, grep and head
Commands that accept both forms work with < as well:
sort < fruits.txt
Output:
apple
apple
fig
pear
The grep command shows the naming difference again. With a file argument and the -H option, it prints the file name. When reading from standard input, it uses the label (standard input):
grep apple < fruits.txt
grep -H apple < fruits.txt
Output:
apple
apple
(standard input):apple
(standard input):apple
Placing the Redirection First
As with output redirection, the position of < on the command line does not matter to Bash. This form puts the input at the beginning, so the line reads like "from this file, take the first two lines":
< fruits.txt head -n 2
Output:
pear
apple
Most people write the redirection after the command, but you will see the other style in scripts and in pipelines that start with a file.
Input and Output Together
You can use < and > in the same command. The command reads from one file and writes to another:
sort < fruits.txt > sorted.txt
cat sorted.txt
Output:
apple
apple
fig
pear
Be careful not to name the same file on both sides. Bash empties the output file before the command starts, so the input file would be empty by the time the command reads it:
sort < fruits.txt > fruits.txt
This command destroys the contents of fruits.txt. The previous lesson shows the safe pattern of writing to a temporary file and then moving it.
When the Input File Is Wrong
If the file does not exist, Bash reports the error itself and does not start the command:
cat < nothere.txt
echo "status: $?"
Output:
bash: nothere.txt: No such file or directory
status: 1
Notice that the message begins with bash:, not with cat:. The error came from the shell, not from the program, which is how you can tell a redirection problem from a command problem. If the name belongs to a directory, the shell opens it successfully but the command fails when it tries to read:
mkdir adir
cat < adir
Output:
cat: -: Is a directory
The - in the message is the name cat gives to standard input.
Reading Lines with read
The built-in read command reads one line from standard input. With a redirection, it reads from the file:
read -r first < fruits.txt
echo "first=$first"
Output:
first=pear
Each < fruits.txt opens the file again from the beginning. A second command therefore starts over:
read -r again < fruits.txt
echo "again=$again"
Output:
again=pear
It printed pear again, not apple, because it was a new redirection. To read the file line by line, you need one redirection that stays open for the whole loop, which is the next topic.
Reading a File in a while Loop
A while loop can take its input from a file by placing the redirection after done:
while IFS= read -r line; do
echo "got: $line"
done < fruits.txt
Output:
got: pear
got: apple
got: fig
got: apple
The file is opened once, when the loop starts, and every read continues where the previous one stopped. The parts IFS= and -r keep leading spaces and backslashes in each line unchanged. A later lesson on reading files line by line explains them in depth.
Because the loop runs in the current shell, variables set inside it are still available afterward:
count=0
while read -r line; do count=$((count+1)); done < fruits.txt
echo "count=$count"
Output:
count=4
If you feed the loop with a pipe instead, the loop runs in a subshell, which is a separate copy of the shell, and the counter is lost:
count=0
cat fruits.txt | while read -r line; do count=$((count+1)); done
echo "count=$count"
Output:
count=0
This is one reason < file is often better than cat file | for loops.
Commands Inside a Loop Share the Input
Inside a loop that reads from a file, any command that also reads standard input shares the same open file and takes lines away from the loop. In this example, head -n 1 consumes one line on every pass:
printf 'a\nb\nc\n' > three.txt
while read -r line; do
echo "outer: $line"
head -n 1 > /dev/null
done < three.txt
Output:
outer: a
outer: c
The line b was swallowed by head. The fix is to give the loop its own file descriptor and read from it with <&3:
while read -r line <&3; do
echo "outer: $line"
head -n 1 < /dev/null
done 3< three.txt
Output:
outer: a
outer: b
outer: c
Here 3< three.txt opens the file on descriptor 3 for the whole loop, read ... <&3 takes each line from it, and the inner command keeps using the real standard input, so nothing is lost. Descriptors above 2 are free for your own use. A later lesson on safely looping through command output uses this idea again.
Naming Descriptor 0
The short form < is the same as 0<, where 0 is the descriptor for standard input:
wc -l 0< fruits.txt
Output:
4
Most scripts leave the 0 out. It is useful to know when you read examples that spell it out, and for saving and restoring descriptors later.
Scripts That Read Standard Input
A script reads standard input in the same way as any other command, so you can feed it a file. This script reads two lines:
read -r a
read -r b
echo "a=$a b=$b"
Saved as readtwo.sh and run with a file on standard input:
bash readtwo.sh < words.txt
Output:
a=alpha beta b=gamma delta
Each read took the next line from the same stream. Run in a terminal, the same script would wait for you to type two lines.
Redirecting for the Rest of the Script
The built-in exec with only a redirection changes the streams for the current shell instead of for one command. This example does it inside parentheses so that it only affects a subshell:
( exec < fruits.txt; read -r x; read -r y; echo "x=$x y=$y" )
Output:
x=pear y=apple
After exec < fruits.txt, every command in the subshell reads from the file, and both read commands continued through it. Used at the top of a script, exec < file makes the whole script read from that file. Keep this form for later: it is powerful, but harder to follow than a loop with done < file.
Related Ways to Supply Input
The < operator needs an existing file. Two related operators supply the text directly in the script, without a separate file. Here documents, written <<, and here strings, written <<<, each have their own lesson. Pipes, written |, connect the output of another command to the input, and also have their own lesson.