Create an error log function for your scripts. Something like:
logerr () {
printf '%s - %s - %s\n' \
"$(date '+%F:%T')" \
"$(basename "$0")" \
"$*" >&2
}
Then you call that from your scripts like:
if false; then
: something for pass
else
logerr failed to be false
fi
Also using 2>error_log
will overwrite error_log
every time. You need to use 2>>error_log
to append.
If you want to be able to capture errors from other commands and error log them you could hack together something like this:
#!/bin/bash
logerr () {
local message=$*
if [[ ! -t 0 ]]; then
message=$(</dev/stdin)
fi
if [[ -n "$message" ]]; then
printf '%s - %s - %s\n' \
"$(date '+%F:%T')" \
"$(basename "$0")" \
"$*" >&2
fi
}
ls -lts /fake/path 2>&1 >/dev/tty | logerr
Ensuring you redirect stdout to whatever applicable location you need it at.
This will allow the logerr
script to read from stdin if it is open (allowing you to pipe programs into logerr). The problem is the programs will send error messages to stderr and you want that to remain separate from stdin.