Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you redirect STDERR for an entire Bash session?

Tags:

bash

stderr

There are lots of questions regarding redirecting stderr and stdout for a single command or script. What I'd like is to redirect any stderr messages from my Bash session to a log file.

I'd like an interactive bash session where all stderr is redirected to a file.

like image 572
RoraΖ Avatar asked Oct 01 '15 14:10

RoraΖ


1 Answers

A horrible way to deal with your problem:

exec 3>&2
trap 'exec 2>>/path/to/your_file' DEBUG
PROMPT_COMMAND='exec 2>&3'
  • exec 3>&2: we first copy fd 2 to a new fd (here fd 3)
  • trap 'exec 2>/dev/null' DEBUG: Before each command is executed (and if the shell option extdebug is set, which is the default in interactive shells), the DEBUG trap is executed: here we redirect stderr to the file /path/to/your_file (make sure you give an absolute path).
  • Before each prompt is displayed, Bash executes the string in the PROMPT_COMMAND variable: here we redirect fd2 to fd3 (and fd3 was a copy of fd2 when it pointed to the terminal). This is necessary to print the prompt.

I wouldn't qualify this as a robust or nice method, yet it might do the job for your purpose.

like image 174
gniourf_gniourf Avatar answered Oct 15 '22 12:10

gniourf_gniourf