我必须在 R 中运行一个 shell 脚本。我考虑过使用 R 的 system
函数。
但是,我的脚本涉及 source activate
和/bin/sh shell 中不可用的其他命令。有什么方法可以改用/bin/bash 吗?
谢谢!
最佳答案
调用/bin/bash
,并通过-c
选项以下列方式之一传递命令:
system(paste("/bin/bash -c", shQuote("Bash commands")))
system2("/bin/bash", args = c("-c", shQuote("Bash commands")))
如果您只想运行 Bash 文件,请为其提供 shebang ,例如:
#!/bin/bash -
builtin printf %q "/tmp/a b c"
并通过将脚本的路径传递给 system
函数来调用它:
system("/path/to/script.sh")
暗示当前用户/组有足够的permissions执行脚本。
理由
之前我建议设置SHELL
环境变量。但它可能行不通,因为 R 中 system
函数的实现调用了 the C function具有相同的名称(参见 src/main/sysutils.c
):
int R_system(const char *command)
{
/*... */
res = system(command);
和
The
system()
library function usesfork(2)
to create a child process that executes the shell command specified in command usingexecl(3)
as follows:
execl("/bin/sh", "sh", "-c", command, (char *) 0);
(参见man 3 系统
)
因此,您应该调用/bin/bash
,并通过-c
选项传递脚本主体。
测试
让我们使用特定于 Bash 的 mapfile
列出 /tmp
中的顶级目录:
测试.R
script <- '
mapfile -t dir < <(find /tmp -mindepth 1 -maxdepth 1 -type d)
for d in "${dir[@]}"
do
builtin printf "%s\n" "$d"
done > /tmp/out'
system2("/bin/bash", args = c("-c", shQuote(script)))
test.sh
Rscript test.R && cat /tmp/out
示例输出
/tmp/RtmpjJpuzr
/tmp/fish.ruslan
...
原始答案
尝试设置SHELL
环境变量:
Sys.setenv(SHELL = "/bin/bash")
system("command")
然后应该使用指定的 shell 调用传递给 system
或 system2
函数的命令。
关于r - 指定在 R 中使用哪个 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845452/