bash 中的 Grep R 错误消息以停止管道

Grep R error message in bash to halt a pipeline

我有一个正在处理的管道。我有一个 wrappper.sh 将各种 .R 脚本通过管道连接在一起。但是,此管道将 运行 通过错误消息。我想添加一种方法来 grep 我们的单词 Error if True,关闭管道。我知道我需要一个 if/else 语句,但不知道如何从 .R 脚本 运行ning in bash.sh 中提取此信息。查看示例错误。

当前脚本:

#!/bin/bash

#Bash script for running GeoMx Pipeline

####
# Install required R packages for pipeline
echo "installing R packages"

Rscript installPackages.R

echo "DONE! R packages installed"

#####
# Created required folders
echo "Creating Folders"

Rscript CreateFolder.R

echo "DONE! Folders created"

####
# Copy data over
cp -u -p Path/Initial\ Dataset.xlsx /PATO_TO

####
# Run Statistical Models

echo "Running Statistical Analysis"

Rscript GLM_EdgeR.R

echo "DONE! Statistical Models completed"

示例错误:

Error in glmLRT(glmfit, coef = coef, contrast = contrast) :
  contrast vector of wrong length, should be equal to number of coefficients in the linear model.
Calls: glmQLFTest -> glmLRT
Execution halted

我想要的:

#!/bin/bash

#Bash script for running GeoMx Pipeline

####
# Install required R packages for pipeline
echo "installing R packages"

Rscript installPackages.R

if grep error == TRUE
then 
   echo "Fatal Error, STOP Pipeline"
   STOP
else 
   echo "DONE! R packages installed"

#####
# Created required folders
echo "Creating Folders"

Rscript CreateFolder.R

if grep error == TRUE
then 
   echo "Fatal Error, STOP Pipeline"
   STOP
else 
   echo "DONE! Folders created"

####
# Copy data over
cp -u -p Path/Initial\ Dataset.xlsx /PATO_TO

####
# Run Statistical Models

echo "Running Statistical Analysis"

Rscript GLM_EdgeR.R

if grep error == TRUE
then 
   echo "Fatal Error, STOP Pipeline"
   STOP
else 
   echo "DONE! Statistical Models completed"

你不需要 grep 错误,你可以测试 last status-code 是否是 non-zero:

#!/bin/bash

Rscript CreateFolder.R

exit_code=$?
if test $exit_code -ne 0
then
  echo "Fatal Error, STOP Pipeline"
  exit $exit_code
else
  echo "DONE! Folders created"
fi

如果 Rscript CreateFolder.R 失败,bash 脚本将以相同的 status-code.

退出

尽管如果您有更多这样的条件要检查,使用 set -e 是有意义的。

Exit immediately if a pipeline, which may consist of a single simple command, a list, or a compound command returns a non-zero status.
https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html

基本上它会让你的脚本 运行 直到出现问题:

#!/bin/bash
set -e
Rscript installPackages.R
echo "DONE! R packages installed"
Rscript CreateFolder.R
echo "DONE! Folders created"
Rscript GLM_EdgeR.R
echo "DONE! Statistical Models completed"

第二个脚本 CreateFolder.R 失败,将如下所示:

~/r# ./wrappper.sh
[1] "OK"
DONE! R packages installed
Error: object 'will_fail' not found
Execution halted