Shell redirection
- Version
- unversioned
- Review
- Draft
Summary#
Redirections connect a command's file descriptors to files or to each other. Descriptor 0 is standard input, 1 is standard output and 2 is standard error.
Syntax#
command < input > output 2> errors
command >> log 2>&1
> truncates or creates a file, >> appends to it, and 2>&1 makes descriptor 2 a copy of whatever descriptor 1 refers to at that moment.
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
emit() {
echo 'to stdout'
echo 'to stderr' >&2
}
emit > out.log 2> err.log
grep . out.log err.log
echo '-- both streams in one file'
emit > all.log 2>&1
cat all.log
echo '-- reversed order'
captured=$(emit 2>&1 > only-out.log)
echo "captured: $captured"
echo "file: $(cat only-out.log)"
echo '-- append, then read from a file'
echo 'appended' >> all.log
tr '[:lower:]' '[:upper:]' < all.log
)
Expected output#
out.log:to stdout
err.log:to stderr
-- both streams in one file
to stdout
to stderr
-- reversed order
captured: to stderr
file: to stdout
-- append, then read from a file
TO STDOUT
TO STDERR
APPENDED
Common mistakes#
Redirections apply from left to right. > file 2>&1 sends both streams to the file, while 2>&1 > file leaves errors on the original standard output. Also, sort data > data empties the file before sort reads it; use sort -o data data instead.
Version applicability#
The operators in this entry work in POSIX-style shells such as sh and Bash. The shorthand &> is a Bash form; a shell such as dash instead reads command &> file as a background command followed by a truncating redirection.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0