r - 指定在 R 中使用哪个 shell

标签 r bash shell

我必须在 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 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 系统)

因此,您应该调用/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 调用传递给 systemsystem2 函数的命令。

关于r - 指定在 R 中使用哪个 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845452/

相关文章:

r - 具有挑战性的载体修饰

r - 是否可以在不使用函数的情况下将 R 回归摘要复制/粘贴到 Excel?

Bash:递归查找文件中列的最大值

python - 子进程中 `shell` 中的 `shell=True` 是否表示 `bash` ?

python - 使用 Paramiko 向 BOSCLI shell 发送命令

r - 从 r 类 GAMM 的随机效应中提取标准误差

r - ggplot2:在同一页面中绘制多个直方图,但一个具有倒置坐标

linux - awk 在 bash 脚本中使用引号和空格

bash - 为什么当我在 bash 脚本中调用另一个函数中的函数时没有获得值

regex - 如何在 sed 解释器脚本的 shebang 中使用 Posix 扩展正则表达式?