Append text to stderr redirects in bash

前端 未结 4 1223
青春惊慌失措
青春惊慌失措 2020-12-08 17:09

Right now I\'m using exec to redirect stderr to an error log with

exec 2>> ${errorLog}

The only downside is that I have to start each

4条回答
  •  失恋的感觉
    2020-12-08 17:39

    This is very interesting. I've asked a guy who knows bash quite well, and he told me this way:

     foo() { while IFS='' read -r line; do echo "$(date) $line" >> file.txt; done; };
    

    First, that creates a function reading one line of raw input from stdin, while the assignment to IFS makes it doesn't ignore blanks. Having read one line, it outputs it with the appropriate data prepended. Then you have to tell bash to redirect stderr into that function:

    exec 2> >(foo)
    

    Everything you write into stderr will now go through the foo function. Note when you do it in an interactive shell, you won't see the prompt anymore, because it's printed to stderr, and the read in foo is line buffered :)

提交回复
热议问题