If you have an R script which you want to run in a Linux bash terminal and if you want in the same time to save the standard output and the standard error in a log file, here is the command to use:
Rscript some_script.R |& tee -a some_script.log
A bit of explanation: the pipe "|" writes by default to the standard output. By using "|&", which is a shorthand for 2>&1 you make sure that both the standard output and the standard error are redirected to the same file.
tee is a command which is used to read the standard input and write it to the standard output and to to one or more files. The "-a" option indicates that the data should be appended to the file. If this is not clear to you, let's try the following:
echo "print('step 1')" >> some_script.R
echo "message('step 2')" >> some_script.R
echo "stop('something went wrong')" >> some_script.R
Rscript some_script.R | tee -a some_script.log
# [1] "step 1"
# step 2
# Error: something went wrong
# Execution halted
cat some_script.log
# [1] "step 1"
Since we used the pipe alone ("|"), only the standard output was written to the log file. Notice that the output of the "message" command is send to the standard error,
so it is not written to the file.
If we instead use "|&", as explained above, both the standard output and the standard error are written to the file:
cat some_script.log
# [1] "step 1"
rm some_script.log
Rscript some_script.R |& tee -a some_script.log
#[1] "step 1"
#step 2
#Error: something went wrong
#Execution halted
cat some_script.log
#[1] "step 1"
# step 2
# Error: something went wrong
# Execution halted
If you are looking for a way to run R code or an R script in the background, check also callr::rscript_process and callr::r_bg
Make a promise. Show up. Do the work. Repeat.