Search notes:

Bash redirection

Notation

fd> fileName

cmd fd> fileName creates a file with name fileName and redirects file descriptor fd (which is a number) to this file.
If the file exists, it will be deleted before it is created again.
If fd is not given, it defaults to 1.
There must be no space between fd and the >. Spaces between > and fileName are possible.

fd>> fileName

cmd fd>> fileName appends file descriptor to the file with name fileName
If the file didn't exist, it is created.
If fd is not given, it defaults to 1.

fdA>&fdB

fdA>&fdB redirects file descriptor fdA to file descriptor fdB.
If fdA is omitted, it defaults to 1.
There must be no spaces between fdA, > and fdB.

An example

Executing commands and redirect their output

The following snippet executes the shell script cmd four times, each time with a different redirectios to stdout and stderr.
#!/bin/bash

./cmd  >       stdout
./cmd  2>      stderr
./cmd   >      stdout-and-stderr          2>&1
./cmd  &>      stdout-and-stderr.too
./cmd  >&      stdout-and-stderr.as-well
Github repository about-Bash, path: /redirection/exec-cmd

cmd

This is the content of cmd:
#!/bin/bash

>&1 echo "This line goes to std OUT"
>&1 echo "Another line that goes to std OUT"
>&2 echo "This line goes to std ERR"
>&1 echo "To std OUT, again"
Github repository about-Bash, path: /redirection/cmd

Three angle brackets / here string

Three consecutive angle brackets (<<<) followed by a word is a so called here string (which is a bit similar to a here document). word is expanded and fed to the command on standard input.
The following example calculates an arithmetic expression:
bc <<< "7.3 * 8.2"
Here strings come in handy to assign values to variables with the read built in.

TODO

sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file: grep -v '^#' input | sponge input
Compare with in place editing with sed and Perl or PowerShell.

See also

PowerShell's redirection operators
bash

Index