koola
koola

Reputation: 1734

Bash - redirect stdout to log and screen with stderr only to log

I would like to do the following;

  1. Redirect a copy of stdout to logfile and keep stdout on the screen.
  2. Redirect stderr to the same logfile and not display on the screen.

Code without stdout to screen:

#!/bin/bash
exec 1> >(sed -u 's/^/INF: /' >> common.log)
exec 2> >(sed -u 's/^/ERR: /' >> common.log)
echo "some txt"
echo "an error" >&2
echo "some more txt"
echo "one more error" >&2

Log:

INF: some txt
INF: some more txt
ERR: an error
ERR: one more error

The first issue is buffering which I tried to negate with sed '-u' for unbuffered.

Code with stdout to screen:

#!/bin/bash
exec 1> >(sed -u 's/^/INF: /' | tee -a common.log)
exec 2> >(sed -u 's/^/ERR: /' >> common.log)
echo "some txt"
echo "an error" >&2
echo "some more txt"
echo "one more error" >&2

Results in the screen hanging (had to Ctrl-C) and log still buffered. Suggestions?

Upvotes: 2

Views: 848

Answers (1)

beatgammit
beatgammit

Reputation: 20205

Does this work for you?

command 2> >(sed -u 's/^/ERR: /' >> common.log) | sed -u 's/^/INF: /' | tee -a common.log

Where command is your command.

Upvotes: 2

Related Questions