在 bash 脚本中运行 R 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20803153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:06:22  来源:igfitidea点击:

Running R scripts within a bash script

linuxrbash

提问by user27976

I have 2 R scripts in the sub-folders of folder1, and ran the following script. "No such file or directory" error was returened for the R scripts. Does anyone know how to solve this problem? Thanks

我在 folder1 的子文件夹中有 2 个 R 脚本,并运行了以下脚本。R 脚本返回“没有这样的文件或目录”错误。有谁知道如何解决这个问题?谢谢

Bash script:

bash脚本:

#! /usr/bin/env Rscript
for dir in folder1/* ; do
Rscript script1.R
Rscript script2.R
done

回答by Dirk Eddelbuettel

You #!specifies R, not bash. And your loop is wrong.

#!指定的是 R,而不是 bash。而你的循环是错误的。

Maybe try this:

也许试试这个:

#!/bin/bash Rscript
for dir in folder1/script*.R ; do
    echo "Now running $dir"
    Rscript folder1/$dir
done

回答by dogbane

Are script1.Rand script2.Rinside the subdirectories of folder1? If so, try this:

script1.Rscript2.R在 的子目录中folder1吗?如果是这样,试试这个:

#! /bin/bash
for dir in folder1/* ; do
    Rscript "$dir"/script1.R
    Rscript "$dir"/script2.R
done

Another way to run all R scripts inside folder1is to use find:

在内部运行所有 R 脚本的另一种方法folder1是使用find

find folder1 -type f -name "*.R" -exec Rscript {} \;

回答by Michael Schlottke-Lakemper

You never changed the directory, so you should either switch to the new subfolder before executing the scripts or execute them using the full path.

您从未更改过目录,因此您应该在执行脚本之前切换到新的子文件夹,或者使用完整路径执行它们。

Thus, try to replace

因此,尝试更换

Rscript script1.R
Rscript script2.R

either by

或者通过

cd folder1/$dir; Rscript script1.R; cd -
cd folder1/$dir; Rscript script2.R; cd -

or

或者

Rscript folder1/$dir/script1.R
Rscript folder1/$dir/script2.R

Also, your shebang is wrong, it should be

另外,你的shebang是错的,应该是

#!/bin/bash

or something similar if you want your script to be a shell script. Right now it is executed as an Rscript.

或者类似的东西,如果你想让你的脚本成为一个 shell 脚本。现在它作为R脚本执行。