0

I have a question like this " What is the correct syntax to redirect both standard output and standard error into the same file both?" and the answer is >both 2>&1 why is this answer correct please explain to me?

What does it mean? >both 2>&1

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
S D
  • 11
  • 1
  • 2
    It means you redirect `stdout` to `both` and then you redirect `stderr` to the same place as `stdout` (order matters here). Check out the documentation on redirection, https://www.gnu.org/software/bash/manual/html_node/Redirections.html. – frippe Mar 01 '22 at 12:17

1 Answers1

1

>file means redirect standard output to the given file. And 2>&1 means redirect standard error to the same descriptor as standard output.

Files are internally (in code) manipulated by descriptors. When you open a file, system gives you in return a descriptor (an object to read/write the file). Linux gives you three descriptors by default: 0 (standard input), 1 (standard output), and 2 (standard error). These 3 descriptors are generally connected to the terminal. Shells (like bash) give you the ability to redirect (change the connection) of them by the use of <, >, and 2> operators (that correspond to open()). These must be followed by a filename, but you can use a special syntax to connect one to another making both aliases to the same file; thus 2>&1 means duplicate descriptor 1 to descriptor 2 (internally this operation is a call to dup()).

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69