15

A while ago I made a script and I added some logging around it, but I forgot how the redirection for the logging works :-(

The gist of it is:

#!/bin/bash

LOGFILE=/some/path/mylogfile

(
  # here go my commands which produce some stdout
  # and, if something goes wrong, also some stderr
) 1>>${LOGFILE} 2> >( tee -a ${LOGFILE} >&2 )

When I run the script, it doesn't print anything to stdout, but only prints what goes to stderr. Logfile ${LOGFILE} captures both stdout and stderr.

When I run the script and there is no output on my terminal, then I know everything is fine. If there is any output, I know something went wrong and I can check the logfile to find out what the problem is.

The part of the redirection that now puzzles me is the syntax of: 2> >( some command )

Can anyone explain what is going on there?

20

>(...) is called process substitution. It lets the "outer" program write to the "inner" program as if it were a file.

In this case it's writing stderr to tee -a ${LOGFILE} >&2 which will append to LOGFILE and then also write everything back to stderr.

The redirection operator can go in either direction for process substitution, so you can write to it, as in this example, or use <(...) to read from it, which is a handy way to, for example, do a while loop without running it in a subshell itself.

  • 5
    Got it :-) If I execute echo <(date), it gives me the name of the substituted file: /dev/fd/63. If I execute cat <(date), it gives me the date, i.e. the content of the substituted file: Fri Nov 18 14:11:09 NZDT 2016. – NZD Nov 18 '16 at 1:21
  • @NZD, yes - but don't imagine it's a regular file - what you see in /dev is a name for the pipe between the processes. – Toby Speight Nov 18 '16 at 8:36
  • Is this technique used because stderr cannot be piped (to tee, in this case)? – bli Nov 23 '16 at 12:58
  • @bli Yeah, since stdout is already being redirected elsewhere this seems to me like the most straightforward way to tee stderr and keep it separate from stdout. – Eric Renouf Nov 23 '16 at 13:00

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.