I'm quite new to this shell scripts. I have 4 scripts A10 to A40 written in R. Each file throws lots of messages in the interim. I want to write a script to execute all these 4 files sequentially and capture all the messages in a log file separately. The name of the log file should be ABC-yyyy-mm-dd-hh-mm-ss.log
. It should not be overwritten next time when I execute the shell script. I searched in the google but couldn't find any document that could help me.

- 12,209
- 10
- 24
- 44

- 321
- 2
- 11
-
How are you currently invoking your scripts. By calling `rscript.exe`? – Mathias R. Jessen Sep 21 '22 at 11:07
-
I'm not sure how to invoke the scripts. – Luiy_coder Sep 21 '22 at 11:09
-
Can you edit the R scripts? Rather than trying to capture all Powershell output in one file, it might be preferable to create the log file inside each R script using the `sink()` function, so you can easily distinguish the log for each script and choose whether you want to log messages, output or both. – SamR Sep 21 '22 at 11:24
1 Answers
Consider the following PowerShell script enumerating multiple Rscript
command steps with all output (information, warnings, errors) redirected to a date-stamped log file. As information, Rscript.exe is the batch job executable, designed to run .R scripts at command line. See R.exe, Rcmd.exe, Rscript.exe and Rterm.exe: what's the difference?.
Below assumes you have the R installation bin folder (where Rscript.exe
sits) in Path
environment variable for PowerShell to recognize Rscript
. Also echo
commands are added to timestamp each R script run. Please adjust file names and paths as needed.
PowerShell (save as .ps1)
cd "C:\path\to\working\directory"
& {
echo "`nExecution Start: $(Get-Date -format 'u')"
echo "`nSTEP 1: R_A10_Script.R - $(Get-Date -format 'u')"
Rscript Run_A10_Script.R
echo "`nSTEP 2: Run_A20_Script.R - $(Get-Date -format 'u')"
Rscript Run_A20_Script.R
echo "`nSTEP 3: Run_A20_Script.R - $(Get-Date -format 'u')"
Rscript Run_A30_Script.R
echo "`nSTEP 4: Run_A20_Script.R - $(Get-Date -format 'u')"
Rscript Run_A40_Script.R
echo "`nExecution End: $(Get-Date -format 'u')"
} 3>&1 2>&1 > "ABC-$(Get-Date -format 'yyyy-MM-dd-HH-ss').log"
To run above script, simply call PowerShell.exe
at command line, referencing .ps1 script with -File
argument. In Windows Explorer, you can hold Shift + Right Click on mouse/touchpad and select "Open PowerShell here" to launch PS terminal in any directory:
PowerShell -ExecutionPolicy bypass -File RunRScripts.ps1

- 104,375
- 17
- 94
- 125
-
Thank you for the answer. How to save this file? I mean using what extension? – Luiy_coder Sep 22 '22 at 04:26
-
See my [edits](https://stackoverflow.com/posts/73803802/revisions) explaining how to run the script. – Parfait Sep 22 '22 at 13:18