从 bash 调用 R 脚本时退出代码

Exit code when calling R script from bash

我有一个从交互式 bash shell (MacOS Catalina) 调用的 R 脚本。这是我从交互式 shell 调用的一系列脚本之一,所以我需要知道初始脚本是否失败。似乎无论脚本如何失败(assert_that,停止,stopfinot,退出),R总是returns退出状态为0。我怎么能return一个非零存在失败的 R 脚本的状态?

这是一个示例 R 脚本 (fail.r)。

#!/usr/bin/env Rscript

#library(assertthat)

message("Starting script")

#assert_that(FALSE)

#stop('Fail')

#stopifnot(FALSE)

q(save="no", status=10, runLast=FALSE)

message("Should not reach here")

下面是我在 bash 提示符下调用它的方式

src/poc/fail.r

echo $?

无论我使用何种方法退出 R 脚本 $?总是 returns 0.

其他一些帖子解决了这个问题,但似乎不适用于我的情况 (How to get an Rscript to return a status code in non-interactive bash mode) and (Make R exit with non-zero status code)

我可以从 Rscript 返回调用 shell(R 版本 4.0.2,bash 版本 3.2.57 或 zsh 版本 5.8 运行 在 MacBook Pro 上, macOS Mohave 10.14.6) 使用 q(status = N)。要从失败的 R 脚本中获取 non-zero 退出状态,请使用 q(status = 2) 或更高版本,请参阅 quit:

$ Rscript -e 'q(status = 0);'
$ echo $?
0

$ Rscript -e 'q(status = 2);'
$ echo $?
2

$ Rscript -e 'q(status = 10);'
$ echo $?
10

$ R --version
R version 4.0.2 (2020-06-22) -- "Taking Off Again"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin13.4.0 (64-bit)

$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)

$ zsh --version
zsh 5.8 (x86_64-apple-darwin17.7.0)

使用与您发布的脚本基本相同的脚本,我得到了预期的结果(来自 quit 的状态已成功传递到封闭的 shell):

脚本:

#!/usr/bin/env Rscript

message("Starting script")
## Use status = 0, 2 or 10:
q(save = "no", status = 2, runLast = FALSE)
message("Should not reach here")

输出(使用上面显示的 zsh 和 bash 版本测试):

$ ~/test/test1.r
Starting script
$ echo $?       
0
$ ~/test/test1.r
Starting script
$ echo $?       
2
$ ~/test/test1.r
Starting script
$ echo $?       
10

另请参见:

Some error status values are used by R itself. The default error handler for non-interactive use effectively calls q("no", 1, FALSE) and returns error status 1. Error status 2 is used for R ‘suicide’, that is a catastrophic failure, and other small numbers are used by specific ports for initialization failures. It is recommended that users choose statuses of 10 or more.

Valid values of status are system-dependent, but 0:255 are normally valid.

(来自 quit 文档)