Chapter 3. Standard Input
Whether it is data for a program to crunch, or simple commands to direct the behavior of a script, input is as fundamental as output. The first part of any program is the beginning of the “input/output” yin and yang of computing.
3.1 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 the <
takes input from a file. The choice and shape of the characters were 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 be invoked as either command filename
or 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 of shell scripting (which the DOS command line borrowed) and was radical in both its power and its simplicity when first introduced.
3.2 Keeping Your Data with Your Script
Problem
You need input to your script, but don’t want a separate file.
Solution
Use a here-document with the <<
characters, redirecting the text from the command ...
Get bash Cookbook, 2nd Edition 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.