28

What's the difference of redirect an output using >, &>, >& and 2&>?

RolandoMySQLDBA
  • 43,883
  • 16
  • 91
  • 132
The Student
  • 27,520
  • 68
  • 161
  • 264

2 Answers2

56
  • > redirects stdout to a file
  • 2>& redirects file handle "2" (almost always stderr) to some other file handle (it's generally written as 2>&1, which redirects stderr to the same place as stdout).
  • &> and >& redirect both stdout and stderr to a file. It's normally written as &>file (or >&file). It's functionally the same as >file 2>&1.
  • 2> redirects output to file handle 2 (usually stderr) to a file.
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 2
    More details here: http://tldp.org/LDP/abs/html/io-redirection.html and http://tldp.org/LDP/abs/html/ioredirintro.html – lecodesportif Jan 20 '11 at 15:59
  • 1
    Does the ampersand signify a file handle, or what does & mean exactly? – Banjer Jan 20 '11 at 16:43
  • 1
    @Banjer: The ampersand usually indicates that the redirection will apply to more than 1 file handle, but the exact semantics depend on the usage of it. – mipadi Jan 20 '11 at 16:47
  • I prefer > to redirect stdout and 2> for standard error and avoid the & – shantanuo Jan 24 '11 at 11:43
  • `&>` and `>&` are quite different but your answer makes it seem like they are the same. – M.M Jul 11 '19 at 06:32
  • @M.M: What is the difference? – mipadi Jul 15 '19 at 20:21
  • 2
    @mipadi [see here](https://stackoverflow.com/questions/24793069/). In brief, `>&` has a right-hand argument of a file *descriptor*, and an optional left-hand descriptor. Whereas `&>` has a right-hand file *name* and no optional left-hand. (Both operators can have a command as the left hand). Your claim "`2&>` redirects file handle 2[...]" is wrong, in that usage the 2 is syntactically part of the command – M.M Jul 16 '19 at 01:39
  • Try `echo foo 2&>bar; cat bar` – M.M Jul 16 '19 at 01:45
  • @lecodesportif, please don't link the ABS. The #bash IRC channel built an entire competing resource -- the [Wooledge BashGuide](https://mywiki.wooledge.org/BashGuide) -- after getting fed up with the time spent trying to get people to unlearn bad practices they picked up from the ABS's examples. – Charles Duffy Sep 14 '22 at 16:24
1

1> (or >) is for stdout, the output of a command. 2> is for stderr, the error output of the command.

This page is a bit wordy, but has good explanations and examples of the different command combinations.

JohnK813
  • 1,134
  • 7
  • 13