Input redirection

Standard input, or stdin, is what is commonly taken from a user’s keyboard and placed into the terminal manually. A simple example is to use cat without arguments: it will then go into interactive mode and wait for user manual input into the program (which can be terminated with CTRL-D).

Basic input redirection (<)

The < operator is used to redirect input from a file rather than the keyboard. For example, instead of using cat and then inputting text, we can do cat < ./textfile.txt to redirect the textfile into cat1.

A more complex example is to redirect the content of a file into a more complex command:

mail -s "Subject line" contact@emailaddress.com < message.txt

Here-document redirection (<<)

The << operator is used to redirect multi-line input directly into a command. To do this, we also have to specify delimiters to designate exactly which part of the document is being redirected. For instance:

cat <<EOF
First line
Second line
EOF

This defines EOF as the delimiter and thus everything up to the final EOF will be included.

Here-string redirection (<<<)

We can use <<< to feed data from a string directly into a command. Using bash, for example, we can use grep to search within a string:

grep 'test' <<< 'search for lines with the word test'

We can also this to pass a longer string individually for a specific file:

mysql -u admin -P <<< "CREATE TABLE IF NOT EXISTS test; SELECT * FROM test;"

Output redirection

The standard output of a terminal is to write to stdout. However, if we want date to flow into other commands or files, we have a few options:

OperatorDescription
>Overwriters existing content
>>Appends content to end of existing file
2> / 2>>Sends error messages (stderr) to separate location
&> / &>>Capture both stdout and stderr

Footnotes

  1. Obviously ignoring the simple cat ./textfile.txt option.