Bash – Meaning of ‘2> >(command)’ Redirection in Bash

bashio-redirectionshell-script

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?

Best Answer

>(...) 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.

Related Question