Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send bash stderr to logfile, but only if an error exists

Tags:

bash

stderr

I am using the following code to send stderr to a file.

.script >2 "errorlog.$(date)"

The problem is that a blank log file is created every time I run the script, even if an error doesn't exist. I have looked online and in a few books as well, and can't figure out how to create a log file only if errors exist.

like image 211
bkstack Avatar asked Jul 10 '13 16:07

bkstack


1 Answers

Output redirection opens the file before the script is run, so there is no way to tell if the file will receive any output. What you can do, however, is immediately delete the file if it winds up being empty:

logfile="errorlog.$(date)"
# Note your typo; it's 2>, not >2
script 2> "$logfile"; [ -s "$logfile" ] || rm -f "$logfile"

I use -f just in case, as -s can fail if $logfile does not exist, not just if it's empty. I use ; to separate the commands because whether or not $logfile contains anything does not depend on whether or not script succeeds.

You can wrap this up in a function to make it easier to use.

save_log () {
    logfile=${1:-errorlog.$(date)}
    cat - > "$logfile"
    [ -s "$logfile" ] || rm -f "$logfile"
}

script 2> >( save_log )
script 2> >( save_log my_logfile.txt )

Not quite as simple as redirecting to a file, and depends on a non-standard feature (process substitution), but not too bad, either.

like image 99
chepner Avatar answered Nov 15 '22 20:11

chepner