Read more

Bash output redirection

Dominik Schöler
May 13, 2014Software engineer at makandra GmbH

There are 3 built-in file descriptors: stdin, stdout and stderr (std=standard). (You can define your own, see the linked article.)

Basic

  • 0/1/2 references stdin/stdout/stderr
  • >/2> redirects stdout/stderr, where > is taken as 1>
  • &1/&2 references stdout/stderr
  • &> redirects stdout and stderr = everything (caution: see below)
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Caution: &> is functional as of Bash 4 Show archive.org snapshot . This seems to result in a slightly differing behaviour when redirecting output in Ruby scripts.
Instead of cmd &> file, prefer cmd > file 2>&1, which equals: "Redirect stdout of cmd to file, and redirect stderr just where stdout is going", e.g. command > /dev/null 2>&1.

Applied to files

  • > creates or overwrites a file
  • >> creates or appends to a file
  • < reads from a file, where < is taken as 0<

Note: You should be pretty sure of what a command is doing if you are going to wipe it's output.

Redirection Examples

  • stdout to file: ls -l > ls-l.txt
  • stderr to file: grep da * 2> grep-errors.txt
  • one to another: grep da * 1>&2
  • everything: do_stuff &> /dev/null
  • combined: command < input-file > output-file, reads from input-file and writes stdout to output-file
Posted by Dominik Schöler to makandra dev (2014-05-13 14:24)