2

I usually use

./aaa.sh 2>&1 | tee -a log

But found a new command which seems easier:

./aaa.sh &> log

So what am I giving up in the second case?

  • 1
    They're not comparable at all. The whole point of tee is to duplicate the input. If the goal isn't to duplicate the input, don't use tee. – n.caillou Dec 20 '17 at 21:47
  • 1
    Its worth remembering that tee is named because it functions sort of like a "T" pipe fitting - i.e. 1 input - 2 outputs. It even says so in the manpage. – Digital Trauma Dec 21 '17 at 1:32
7

Apples and oranges. But first...

As far as 2>&1 vs &>, they both act to direct stderr to the same place that stdout is being directed to.

But you are giving up portability with the second one as it is not POSIX-compliant and any script using it will only work with those shells that support it.

That being said they are "semantically equivalent" as described on the Bash man page...

There are two formats for redirecting standard output and standard error:

      &>word    and
      >&word

Of the two forms, the first is preferred. This is semantically equivalent to

      >word 2>&1

When using the second form, word may not expand to a number or -. If it does, other redirection operators apply (see Duplicating File Descriptors below) for compatibility reasons.

However there's more to it. You also are using the tee command which adds additional functionality to the first version. It will take its stdin input and direct it to two different places: stdout (usually your screen/terminal if you're running this interactively) and the specified file which will have the data appended to it (-a says to append rather than overwrite).

Compare this to the second version where the combined stdout and stderr overwrite the log file and do not get displayed on your screen/terminal.

Conclusion: As mentioned at the beginning these are really two different commands altogether but, stretching the notion of equivalence, generally speaking the first version is superior as it is portable and you get the benefit of seeing the output of aaa.sh even while it is being saved to a file. Of course, if you don't want to see that or you want to erase the previous file contents then it's a different story. Apples and oranges.

| improve this answer | |
  • 1
    And of course a big advantage of tee is that prints both to the screen and file. – Arkadiusz Drabczyk Dec 20 '17 at 21:19
4

Two things:

  • tee prints its input to both the named file, and the standard output, in practice to your terminal. A straight redirection like > or &> only causes the file to be written.

  • tee -a appends to the named file, a > or &> redirection overwrites it. Use >> or &>> or >> file 2>&1 to append with a redirection.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.