Programs do not only produce output. Many of them also read input, and the channel they read from by default is standard input, or stdin. It is file descriptor 0.
Reading from the keyboard
stdin is normally connected to your terminal. Run cat with no file name and it waits for you to type.
$ cat
hello
helloThe first hello is what you typed. The second is cat copying it to stdout. Press Ctrl-D on an empty line to signal end of input. This is not the same as Ctrl-C, which interrupts the program.
Read from a file with <
The < operator connects stdin to a file.
$ cat < fruit.txt
apple
banana
cherryThe shell opens fruit.txt, and cat just reads stdin. If the file does not exist, the shell reports an error and the command never runs.
A visible difference
cat fruit.txt and cat < fruit.txt print the same thing, but the program is doing different work. wc -l, which counts lines, shows this:
$ wc -l fruit.txt
3 fruit.txt
$ wc -l < fruit.txt
3In the first case wc opened the file itself, so it knows the name. In the second it only received a stream of bytes.
You can redirect both directions in one command:
$ sort < fruit.txt > sorted.txtHere-documents and here-strings
A here-document feeds several lines to stdin straight from the command line. Input ends at the word you choose, written alone on a line.
$ sort << END
> pear
> fig
> END
fig
pearThe > at the start of those lines is the shell's continuation prompt, so you do not type it.
Bash and Zsh also have a here-string, <<<, for a single string. Plain POSIX sh, such as dash on Debian and Ubuntu, does not support it.
$ wc -w <<< "one two three"
3More practice is waiting in the streams and text lab.
Try it
- Create a file with
echo "b" > letters.txtandecho "a" >> letters.txt. - Run
sort < letters.txt. - Run
wc -l letters.txtand thenwc -l < letters.txt. - Start
cat, type two lines, and finish withCtrl-D.
Check your understanding
stdin (Standard In)
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.