Chapter 5: Directing Input and Output

5.1 Standard input and standard output

stdin - is standard input. This is the input coming from the keyboard and attached input devices.

stdout - is standard output. This is the output sent to the text window or terminal window.

By default bash works from and to stdin and stdout. However, you may need to work with data from files instead of with data from the terminal.

5.2 Directing output to a file

Direct output to a file using the > operator.

sort mock_companies.csv > mock_companies_sorted.csv

Attention: If the file you are writing to exists the > operator will over-write its contents!

5.2.1 examples:

5.2.1.1 Concatinate two files and direct output to a third file:

cat file1.txt file2.txt > new_file.txt

Concatinates two files and outputs to a new file... it concatinates in the order of the listed files..

5.2.1.2 Direct a text string to a file:

echo "textstring" > file.txt

Over-writes the current contents of a file with the text string.

5.3 Appending to a file

Append output to a file using the >> operator. It is used to append to the end of a file instead of overwriting the file contents.

echo "Claire" >> file.txt

adds "Claire" to the end of the content of file.txt

5.4 Directing input from a file

The < operator takes a file's content as the input for a command.

sort < mock_companies.csv

Takes the content of mock_companies.csv as the argument to the sort command.

Does this look familiar?

patch < drupal_patch.txt

5.5 Directing input and output

You can direct input into a command and then direct the resulting output into a second command:

sort < fruit.txt > sorted_fruit.txt

The order is always INPUT then OUTPUT

The arguments are always files

5.6 Piping output to input

To take the output from one command and send it to another command without printing it to the screen, or a file, we use a pipe | operator.

Pipe a text string into word-count program:

echo "Hello World" | wc

... or, pipe a math function into a calculator program:

echo "(3*4)+(11*37)" | bc

...or,

read text into memory, pipe it to uniq to eliminate duplicates, pipe it to sort:

cat fruit.txt | uniq | sort

...or,

input fruit.txt into uniq and pipe the result to sort and output that to sorted_unique_fruit.txt:

uniq < fruit.txt | sort > sorted_unique_fruit.txt

...or,

pipe the active processes into less:

ps aux | less

ps aux outputs the active processes to terminal but the output is not paginated. Piping the output to less allows us to read the output through less which gives us pagination.

We pipe into a command not into a file.

5.7 Suppressing output

Sometimes you want to run a command and have it execute without getting back any output. You can use the null device (also referred to as a bit_bucket, or blackhole.)

Its a file like stdin and stdout but UNIX discards any info sent there.

ls -la > /dev/null