如何在非交互式bash模式下获取Rscript以返回状态代码 [英] How to get an Rscript to return a status code in non-interactive bash mode

查看:61
本文介绍了如何在非交互式bash模式下获取Rscript以返回状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以非交互方式以bash脚本的形式从Rscript中获取状态代码.此步骤是更大的数据处理周期的一部分,该周期涉及db2脚本.

I am trying to get the status code out of an Rscript run in an non-interactive way in the form of a bash script. This step is part of larger data processing cycle that involves db2 scripts among other things.

所以我在脚本sample.sh中具有以下内容:

So I have the following contents in a script sample.sh:

Rscript --verbose --no-restore --no-save/home/R/scripts/sample.r>>sample.rout

运行此sample.sh时,无论sample.r脚本是否完全运行或在中间步骤中出错,它始终返回状态代码0.

when this sample.sh is run it always returns a status code of 0, irrespective of if the sample.r script run fully or error out in an intermediate step.

我尝试了以下方法,但是没有运气

I tried the following things but no luck

1-在sample.sh文件中,我为以下返回代码添加了一个if和else条件,但是尽管sample.r在其中一个函数中失败,但它再次写回0.

1 - in the sample.sh file, I added an if and else condition for a return code like the below, but it again wrote back 0 despite sample.r failing in one of the functions inside.

if Rscript --verbose --no-restore --no-save /home/R/scripts/sample.r >> sample.rout
then
  echo -e "0"
else
  echo -e "1"
fi

2-我还尝试了包装脚本,例如在sample.wrapper.sh文件中

2 - I also tried a wrapper script, like in a sample.wrapper.sh file

r=0
a=$(./sample.sh)
r=$?

echo -e "\n return code of the script is: $a\n"
echo -e  "\n The process completed with status: $r"

在sample.r失败的情况下,在变量 a r 的中间步骤中,我也没有得到预期的'1'.理想情况下,我想要一种方法来捕获 a 中的错误(为"1").

here also I did not get the expected '1' in the case of failure of the sample.r in an intermediate step on both the variables a and r. Ideally, i would like a way to capture the error (as '1') in a.

有人可以建议仅在完成整个脚本而没有任何错误的情况下如何使rscript写入"0",而在所有其他情况下,如何使rscript写入"1"吗?

Could someone please advice how to get rscript to write '0' only in case of completion of the entire script without any errors and '1' in all other cases?

非常感谢您的投入!谢谢!

greatly appreciate the input! thank you!

推荐答案

我通过返回echo之外的状态代码解决了该问题.以下是从sample.sh脚本中摘录的代码.另外,在sample.R代码中,我添加了trycatch来捕获错误并退出(状态= 1).

I solved the problem by returning the status code in addition to echo. below is the code snipped from sample.sh script. In addition, in sample.R code i have added trycatch to catch the errors and quit(status = 1).

function fun {

if Rscript --verbose --no-restore --no-save /home/R/scripts/sample.r > sample.rout 2>&1
then
  echo -e "0"
  return 0  
else
  echo -e "1"
  return 1
fi

}

fun

感谢大家的投入.

这篇关于如何在非交互式bash模式下获取Rscript以返回状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆