【问题标题】:UNIX commands from R via shell function来自 R 的 UNIX 命令通过 shell 函数
【发布时间】:2018-02-27 18:46:02
【问题描述】:

我需要从 R 会话发出 unix 命令。我在使用 RStudio 1.1.383 和 R 3.4.3 的 Windows R2 2012 服务器上。

shell() 函数看起来对我来说是正确的,但是当我指定 bash shell 的路径(从 Git for Windows 安装)时,命令失败,错误代码为 127。

shell_path <- "C:\\Program Files\\Git\\git-bash.exe"
shell("ls -a", shell = shell_path)
## running command 'C:\Program Files\Git\git-bash.exe /c ls -a' had status 127'ls -a' execution failed with error code 127

很确定我的 shell 路径是正确的:

我做错了什么?

编辑:为清楚起见,我想传递任意数量的 UNIX 命令,我只是使用ls -a 为例。

编辑:

在2018-03-09玩了一些之后:

shell(cmd = "ls -a", shell = '"C:/Program Files/Git/bin/bash.exe"', intern = TRUE, flag = "-c")

我的 bash.exe 的正确位置是 .../bin/bash.exe。这使用 shell 和 intern = TRUE 将输出作为 R 对象返回。请注意在 shell 路径周围使用单引号。

编辑:2018-03-09 21:40:46 UT

在 RStudio 中,我们还可以使用 knitr 调用 bash 并设置块选项:

library(knitr)

```{bash my_bash_chunk, engine.path="C:\\Program Files\\Git\\bin\\bash.exe"}
# Using a call to unix shell
ls -a
```

【问题讨论】:

    标签: r bash rstudio knitr git-bash


    【解决方案1】:

    这里有两点很突出。如果找不到命令,Bash 将返回退出代码 127;您应该尝试运行完全限定的命令名称。

    我还看到您的 shell 正在使用 /c 标志运行。 According to the documentation,flag 参数指定“在 shell 下运行命令的开关”,默认为 /c,但“如果 shell 是 bash 或 tcsh 或 sh,则默认更改为 '-c'。 " git-bash.exe 显然不会发生这种情况。

    试试这些改变:

    shell_path <- "C:\\Program Files\\Git\\git-bash.exe"
    shell("/bin/ls -a", shell = shell_path, flag = "-c")
    

    不在 Windows 上,所以不能确定这是否可行。

    【讨论】:

    • 道歉。是的,并且带有完全限定的 `"/bin/ls -a"
    • 如果您只是尝试使用像echo foo 这样的内置shell 而不是运行ls 会发生什么?
    • 你也可以试试system2(command=shell_path, args=c("-c", shQuote("/bin/ls -a")))
    • echo ... 给出了错误代码 127。system2(... 生成了一个简短的 shell 会话,该会话在没有向 R 控制台返回结果的情况下关闭
    • shell exe 的正确位置是.../bin/bash.exe。将shell 与此一起使用会产生 bash 命令的输出。
    【解决方案2】:

    也许您需要使用shQuote?

    shell( paste("ls -a  ", shQuote( shell_path) ) )
    

    (未经测试。我不在 Windows 上。但请阅读?shQuote))

    【讨论】:

    • OP 不希望得到一个目录列表 of git-bash.exe,想要一个目录列表 using 它。
    【解决方案3】:

    如果你只想做ls -a,你可以使用下面的命令:

    shell("'ls -a'", shell="C:\\Git\\bin\\sh.exe")
    
    #or
    shell('C:\\Git\\bin\\sh.exe -c "ls -a"')
    

    让我们知道“程序文件”中的空间是否导致问题。

    如果你需要登录才能调用你的命令,

    shell('C:\\Git\\bin\\sh.exe --login -c "ls -a"')
    

    但是,如果您正在考虑从 R 中执行 git 命令,ropensci 的 git2r 可能会满足您的需求。

    【讨论】:

    • 我的 sh.exe 位于 @"C:\\Program Files\\Git\\bin\\sh.exe"。所有这些代码块仍然得到错误代码 127。我对 git 命令不感兴趣 - 只需在我的 Windows 机器上安装来自 Git for Windows 的 bash 即可。我想知道空格字符,但在有关该主题的其他 SO 帖子中没有看到它被标记为问题,并且 \\ing 空格没有区别。
    • 也许您想尝试对程序文件使用 ~ 形式?可以离开我的头顶。你需要谷歌。我的 c 驱动器中有 git,以上适用于我 64bit r3.3.2 win7。
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2011-12-11
    • 2014-06-25
    相关资源
    最近更新 更多