Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Standard streams

As described in a section of Linux Fundamentals page, there are three built-in, Standard Streams, Standard streams and redirection each with a well-defined stream number:

  • 0 - standard input
  • 1 - standard output
  • 2 - standard error

Redirection characters allow you to control the stream input or output

...

  • redirect standard output to a file, overwriting any exiting contents:
    echo "Output text" > out.txt
    echo "Some output" 1> out.txt
  • redirect standard output to a file, appending to any exiting contents:
    echo "Some text" >> out.txt
    echo "More text" 1>> out.txt
  • redirect standard error output to a file, overwriting any exiting contents:
    ls xxxx 2> err.txt
  • redirect standard error to standard output:
    ls xxxx > ls.log 2>&1
  • redirect standard output to standard error:
    echo "Output that will go be redirected to standard error" 1>&2
    echo "Output that will go to be redirected standard error" 2> err.txt 1>&2

There's also the tee program, which takes its standard input and writes it to the specified file as well as to its standard output

...

Code Block
languagebash
~/workshop/step_01.sh helloWorld My name is Anna | tee step_01.log

See Piping in the Linux Fundamentals page Standard streams and piping in the Intro Unix wiki.

When standard output and standard error streams are used

Let's look at a command that shows the difference between standard error and standard output:

Code Block
languagebash
# list 2 files, one that exists and one that does not
ls ~/.profile xxx 

...

What is not obvious here, since both streams are displayed on the terminal, is that the diagnostic text "ls: cannot access 'xxx': No such file or directory" is being written to standard error, while the listing of the existing file (text ".profile") is being written to standard output.

...

Code Block
languagebash
ls ~/.profile ~/xxx 1>stdout1>out.txt 2>stderr2>err.txt
cat stdoutout.txt
cat stderrerr.txt

Finally redirect both standard output and standard error to a single file:

Code Block
languagebash
ls ~/.profile ~/xxx >1> ls.log 2>&1
# or
ls ~/.profile ~/xxx 2>1 1> ls.log Note that the 2>&1 syntax has to come **after** the redirection of standard output

# ButSo this does not redirect stdout
ls ~/.profile ~/xxx 2>&1 1> ls.log 

...