Given a file script.R
containing 3 lines :
给定一个包含3行的文件script.R:
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) :
好。它暂停了错误运行脚本。但是shell的返回值是0(成功):
$ 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.
反正有没有运行脚本,停止错误,并返回非零到shell?我搜查了一下,找不到答案。
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.
我可以grep输出文件的文本“错误”,但这有一些需要管理的风险;例如以某种方式greping错误的输出文件并且两次或多次运行写入同一文件。可以管理这些问题,但是将非零返回到shell将更简单,更健壮。在脚本末尾添加一行也是一种解决方法,因为我需要将该行添加到所有脚本中。
1 个解决方案
#1
4
Thanks to @Pascal in comments, it turned out that in my .Rprofile I had :
感谢@Pascal的评论,结果发现在我的.Rprofile中我有:
options(error=quote(dump.frames()))
When I run with --vanilla
as well to prevent my .Rprofile from being loaded :
当我使用--vanilla运行以防止我的.Rprofile被加载:
$ 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!
这正是我想要的并解决问题。谢谢@Pascal!
#1
4
Thanks to @Pascal in comments, it turned out that in my .Rprofile I had :
感谢@Pascal的评论,结果发现在我的.Rprofile中我有:
options(error=quote(dump.frames()))
When I run with --vanilla
as well to prevent my .Rprofile from being loaded :
当我使用--vanilla运行以防止我的.Rprofile被加载:
$ 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!
这正是我想要的并解决问题。谢谢@Pascal!