Kuzey
Kuzey

Reputation: 879

What is the difference between different input/output redirection styles?

What are the differences between these commands:

  1. command 2>&1 > log
  2. command > log 2>&1
  3. command >& log
  4. command > log 1>&2

First one outputting the error to the console and, the output to the log. Why not both doesn't go to the log?

Second one doesn't produce any output, the output and the error are in the in the log. What difference it makes to put 2>&1 at the end?

Third one is same as previous. For what is it a shortcut?

Fourth one puts everything to console and nothing to the log?

example command : ls -ld /tmp /xxx

Upvotes: 1

Views: 344

Answers (2)

l0b0
l0b0

Reputation: 58998

These are very well explained in two articles. Essentially, you have to read the redirects from left to right as copies of an output target. So

command 2>&1 > log
  1. Sets the target of FD 2 (standard error) to the target of FD 1 (standard output), which is usually the terminal.
  2. Sets the target of FD 1 to the file log.

These are not transitive, so standard error really points to the terminal when the command runs.


command > log 2>&1
  1. Sets the target of FD 1 to the file log.
  2. Sets the target of FD 2 (standard error) to the target of FD 1 (standard output), which now is the file log.

This means both standard output and standard error are logged to the same file.


command >& log

Redirects both standard error and standard output to the file log. This is Bash syntactic sugar for the previous command.


command > log 1>&2
  1. Sets the target of FD 1 to the file log.
  2. Sets the target of FD 1 to target of FD 2 (standard error), which is usually the terminal. This overrides the previous redirection.

Upvotes: 4

TrueY
TrueY

Reputation: 7610

The redirection order is important in :

  1. command 2>&1 > log redirects stderr to stdout and then stdout to log file. So the result is stderr goes to the screen (if not redirected on some higher level) and stdout goes to file.
  2. command > log 2>&1 redirects stdout to a file, and the stderr redirected to the file handle 1 which is the file.
  3. command >&log is the shortcut for the previous case, namely it redirects stderr and stdout to the file.
  4. This it the same case as #2
  5. command > log 1>&2 redirects stderr (file handle 1) to a file, then it redirects it to stderr. So as a result stdout will go to stderr. But a zero byte long log file appears. This can be written as command >log >&2.

Upvotes: 2

Related Questions