I have the following (simplified) code attempts in 2 shell scripts below.
The script calls an R script in which code is run that will generate standard output and error stream depending on what happens.
What I'm trying to achieve is to have both the output and error stream display on the console as usual but when the script is run and it fails (e.g. the RScript produces an error stream) I want to save that error message that R generates in a sqlite database but still have the normal output and errors display on the console as well when it exits. I have tried many forms of redirecting output of the Rscript function, but I either end up saving nothing to the database (apart from the line number) or I can save the error message but nothing will be put on the console...
This will not save error message to the DB (line number will), but everything will be on console
updateDBwhenError() {
sqlite3 "myDB.db" "INSERT INTO logs VALUES('$1')"
}
err_report() {
#Tryign to capture both line error and message
updateDBwhenError "Error Line $1 $2"
exit
}
trap 'err_report ${LINENO}' ERR
Rscript testScript.R
This will save the error message to the DB, but nothing will be on console anymore
updateDBwhenError() {
sqlite3 "myDB.db" "INSERT INTO logs VALUES('$1')"
}
err_report() {
#Tryign to capture both line error and message
updateDBwhenError "Error Line $1 $rErr"
exit
}
trap 'err_report ${LINENO}' ERR
rErr=$(Rscript testScript.R 2>&1)
I looked everywhere for a way to capture just the error stream to a variable and keep the output untouched on the console (both output and error), but I'm stuck.
Try this
Test script
Testing with this script