My notes on Linux command output redirection

Outputs

1 is standard output or stdout
2 is standard error or stderr
& is all output

This convention can be used to filter relevant outputs, for example:

COMMAND 2> FILENAME

#this will save any error messages generated by the command to file

COMMAND &> FILENAME
#directs all output to file

COMMAND > FILENAME 2>&1
#directs stderr to same place as stdout

> – Output to File

> redirects the output of a command to a file, OVERWRITING any existing file of the same name, or otherwise creating a new file.

COMMAND > FILENAME
COMMAND 1> FILENAME
#directs standard output to file
COMMAND 1> FILENAME 2> /dev/null
#directs standard output to file and standard error to trash

>> – Append to File

>> redirects the output of a command to a file, APPENDING it to any existing file of the same name or otherwise creating the file.

COMMAND >> FILENAME
COMMAND 1>> FILENAME

< – Process as input

Most input is via keyboard but there are circumstances where one might want input from a file

COMMAND < FILENAME
#this will direct the command to take its input from the file

| – Pipe – Chain Commands

The pipe directs a command to take its input from the preceding command

COMMAND1 | COMMAND2 | COMMAND3

see also 'tee'

; – Semi-Colon – Run Command independently of preceding command

COMMAND1; COMMAND2
#runs both commands

see also 'tee'

tee

tee splits output into two streams; one for display and a copy for file

COMMAND | tee FILENAME
#displays the results of command and SAVES to file

COMMAND | tee -a FILENAME
#displays the results of command and APPENDS to file

date | tee time.txt; sleep 15; date | tee -a time.txt
#displays the date and saves it to time.txt. Pauses, then displays the date again, appending the same to time.txt

xargs

Gather multiple arguments to pass to a command

echo 'noob1 noob2 noob3 noob4' | xargs touch
#passes each of nob1, noob2 etc to touch as an argument, thereby creating four files (if they didn;t exist already)

Act as a delimiter on output

ls | grep noob | xargs -d '-'
#searches all filenames in current directory for noob, then displays the output split using delimiter -

Send output of a command to next command as an argument
COMMAND1 | xargs COMMAND2
#uses the output of COMMAND 1 as the argument for COMMAND2