指定在R中使用哪个shell [英] Specify which shell to use in R

查看:116
本文介绍了指定在R中使用哪个shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在R中运行一个shell脚本.我考虑过使用R的system函数.

I have to run a shell script inside R. I've considered using R's system function.

但是,我的脚本涉及到source activate和/bin/sh shell中不可用的其他命令.有没有办法可以使用/bin/bash代替?

However, my script involves source activate and other commands that are not available in /bin/sh shell. Is there a way I can use /bin/bash instead?

谢谢!

推荐答案

调用/bin/bash,然后以下列方式之一通过-c选项传递命令:

Invoke /bin/bash, and pass the commands via -c option in one of the following ways:

system(paste("/bin/bash -c", shQuote("Bash commands")))
system2("/bin/bash", args = c("-c", shQuote("Bash commands")))

如果您只想运行Bash 文件,请为其提供

If you only want to run a Bash file, supply it with a shebang, e.g.:

#!/bin/bash -
builtin printf %q "/tmp/a b c"

并通过将脚本的路径传递给system函数来调用它:

and call it by passing script's path to the system function:

system("/path/to/script.sh")

这暗示当前用户/组具有足够的权限来执行脚本.

It is implied that the current user/group has sufficient permissions to execute the script.

以前,我建议设置SHELL环境变量.但这可能不起作用,因为R中system函数的实现会调用

Previously I suggested to set the SHELL environment variable. But it probably won't work, since the implementation of the system function in R calls the C function with the same name (see src/main/sysutils.c):

int R_system(const char *command)
{
    /*... */
    res = system(command);

还有

system()库函数使用fork(2)创建一个子进程,该子进程执行使用execl(3)的命令中指定的shell命令,如下所示:

The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows:

execl("/bin/sh", "sh", "-c", command, (char *) 0);

(请参阅man 3 system)

因此,您应该调用/bin/bash,并通过-c选项传递脚本主体.

Thus, you should invoke /bin/bash, and pass the script body via the -c option.

让我们使用特定于Bash的mapfile列出/tmp中的顶级目录:

Let's list the top-level directories in /tmp using the Bash-specific mapfile:

test.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调用传递给systemsystem2函数的命令.

Then the commands passed to system or system2 functions should be invoked using the specified shell.

这篇关于指定在R中使用哪个shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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