Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tee stderr from a trap?

Tags:

bash

logging

I want to log everything going to stderr in the following script:

#!/bin/bash
exec 2> >(tee -a file >&2)
trap '>&2 echo text; exit' INT
read

Pressing ctrl+c will trigger the trap, but the output is lost. Surprisingly, using exec 2>> file, it will end up in the file, yet I need it to be displayed to the user as well.

How can I log stderr, including the trap output, while still displaying it to the user?

like image 470
katosh Avatar asked Sep 03 '25 03:09

katosh


1 Answers

In order for tee to ignore the interrupt signal one can add an additional trap '' INT before it:

#!/bin/bash
exec 2> >(trap '' INT; tee -a file >&2)
trap '>&2 echo text; exit' INT
read

Edit: Contained the trap in the subshell as sugested by @John1024 in the comments.

like image 155
katosh Avatar answered Sep 04 '25 22:09

katosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!