3

I have a question regarding file redirects 2>&1 and 1>&2. I know that file descriptor 1 is std o/p and 2 is std error and that we're redirecting one file descriptor to another.

But why do we do it? What are their use cases? Wouldn't the file to which redirection is setup get too clunky?
Analysis of the file would also become a bit difficult. And wouldn't having errors stored in a separate file make it easier to interpret and fix them?

Comments
  • 2
    2>&1 1>/dev/null is usually used to use an program without an option to silence it.
  • 3
    Sometimes you just don't want that for reasons. For example because you don't need those to be machine-readable and you want to see them exactly as they would appear in terminal.
  • 1
  • 2
    I mean if you're asking specifically why would you redirect out to err and viceversa, a good example would be if you want to pipe the errors to another process that reads them from stdout, and i dunno, add the color red to the lines, but you don't want to colorize the original stdout...

    if said process read from stderr then this wouldn't be necessary.

    I guess it makes sense if it's a heuristic solution to a specific situation
  • 2
    Try running a command:
    strace -fv uptime | less

    the pager will show only uptime output, but no strace's output

    This happens because strace prints output we are using it for to stderr, and shell pipes only connect stdout-->stdin. That way everything strace has printed goes nowhere. So a simple pipes remapping (2>&1) will make all strace's output go straight to stdout so less could pick it up.

    Another case. Suppose you are writing a script. You fire some command and you want to know whether it failed, and if it failed -- parse its error message. Usualy commands print all errors to stderr and normal output to stdout. Your script will want to analyze stdout in case of success and analyze errors in case of errors. Once again, you can only pipe stdOUT->stdin. This applies to variable assignments too. So w/o 2>&1 you'd lose all error messages.

    There are more use cases, I just find those handy for my BAU
  • 1
    @netikras this was quite helpful, thank you
  • 1
    @justasithlord what I said about "reading from stderr" was incorrect, sorry.

    @netikras so then a pipe take the stdout of the left hand command and makes it the stdin of the right hand command?
  • 1
Add Comment