Given a file script.R
containing 3 lines :
print('hello')
stop('user error')
print('world')
we can run it :
$ R -f script.R
> print('hello')
[1] "hello"
> stop('user error')
Error: user error
> print('world')
[1] "world"
but that continues after the error. I want it to halt the script on error. This does that :
$ R -e "source('script.R')"
> source('script.R')
[1] "hello"
Error in eval(expr, envir, enclos) : user error
Calls: source -> withVisible -> eval -> eval
Good. It halted running the script on the error. But the return value to the shell is 0 (success) :
$ echo $?
0
Is there anyway to run the script, halt on error, and return non-zero to the shell? I searched and I couldn't find an answer.
I could grep the output file for the text "Error" but that has some risk that needs managing; e.g. greping the wrong output file somehow and two or more runs writing to the same file. Those issues can be managed but returning non-zero to the shell would be simpler and more robust. Adding a line to the end of the script is also a workaround since I'd need to add that line to all the scripts.
Thanks to @Pascal in comments, it turned out that in my .Rprofile I had :
options(error=quote(dump.frames()))
When I run with --vanilla
as well to prevent my .Rprofile from being loaded :
$ R --vanilla -f script.R
> print('hello')
[1] "hello"
> stop('user error')
Error: user error
Execution halted
$ echo $?
1
Which is exactly what I wanted and solves the problem. Thanks @Pascal!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With