Getting Input from a File

Problem

You want your shell commands to read data from a file.

Solution

Use input redirection, indicated by the < character, to read data from a file

 $ wc < my.file

Discussion

Just as the > sends output to a file, so < takes input from a file. The choice and shape of the characters was meant to give a visual clue as to what was going on with redirection. Can you see it? (Think “arrowhead.”)

Many shell commands will take one or more filenames as arguments, but when no filename is given, will read from standard input. Those commands can then be invoked as either: command filename or as command < filename with the same result. That’s the case here with wc, but also with cat and others.

It may look like a simple feature, and be familiar if you’ve used the DOS command line before, but it is a significant feature to shell scripting (which the DOS command line borrowed) and was radical in both its power and simplicity when first introduced.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.