Skip to content

Linux Foundations / Find your way around Linux ยท Step 32 of 63

Lesson: stdin (Standard In)Switch
โ† Linux Foundations

Shell and files

stdin (Standard In)

Learn how programs read input and how to feed them from files and here-documents.

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
hello

The 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
cherry

The 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
3

In 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.txt

Here-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
pear

The > 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"
3

More practice is waiting in the streams and text lab.

Try it

  1. Create a file with echo "b" > letters.txt and echo "a" >> letters.txt.
  2. Run sort < letters.txt.
  3. Run wc -l letters.txt and then wc -l < letters.txt.
  4. Start cat, type two lines, and finish with Ctrl-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.