Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for R to run a script and on error return non-0 to the shell?

Tags:

r

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.

like image 515
Matt Dowle Avatar asked Sep 27 '22 19:09

Matt Dowle


1 Answers

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!

like image 176
Matt Dowle Avatar answered Oct 12 '22 23:10

Matt Dowle