13

Windows 10 上的 WSL 允许通过 bash.exe 执行 Linux 命令和命令行工具。非常有用的是,可以从 Windows 命令行 ( cmd.exe) 调用 Linux 工具/命令,方法是将其作为参数传递给 bash.exe,如下所示:

bash.exe -c <linux command>

这非常有用,因为它应该允许基于 Windows 的脚本无缝地结合 Windows 和 Linux 工具。

不幸的是,我未能从 R 脚本调用 Linux 命令(见下文)。

0) 系统

Win10 x64 + 周年更新 + WSL 已安装

1)调用Linux命令的比较案例

以下所有内容都对我有用;这里显示的只是一个对ls.

  • 从 Windows 命令行(cmd.exe 提示符)

    bash -c "ls /mnt/a"
    

    bash -c "ls /mnt/a > /mnt/a/test.txt"
    
  • 如果从WinKey + R

  • .bat文件中同样有效。

  • 它可以从编译的代码中调用。我尝试使用 Delphi XE2 32 位和 64 位ShellExecute

    例如,这些工作(32 位和 64 位):

    ShellExecute (0, PChar('open'), PChar('cmd.exe'), PChar('/c c:\windows\system32\bash.exe -c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
    

    或(32 位代码):

    ShellExecute (0, PChar('open'), PChar('c:\windows\sysnative\bash.exe'), PChar('-c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
    

    或(64 位代码):

    ShellExecute (0, PChar('open'), PChar('c:\windows\system32\bash.exe'), PChar('-c "ls /mnt/a > /mnt/a/test.txt"'), nil, SW_SHOWNORMAL);
    

    所有这些似乎都有效(并ShellExecute返回 42)。

2)使用 R 3.3.1 x64从 R 调用 Linux 命令失败

以下所有(以及我尝试过的几个类似的事情)都失败,状态为 65535:

shell('c:/windows/system32/bash.exe -c "ls /mnt/a"', shell="cmd.exe", flag = "/c")

shell("ls", shell="c:/windows/system32/bash.exe", flag = "-c")

system('cmd /c c:/windows/system32/bash.exe -c "ls /mnt/a > /mnt/a/test.txt"')

system('bash -c "ls /mnt/a"')

system('c:/windows/system32/bash.exe -c "ls /mnt/a > /mnt/a/test.txt"')

3) 问题

鉴于1)下的示例有效,我发现2)非常令人费解。我在这里遗漏了什么明显的东西吗?

如果有一个简单的例子,我将非常感谢通过bash.exeWSL 运行 Linux 命令的工作。

4

1 回答 1

9

您失败的示例现在应该在 Windows 10 Insider build >= 14951 中正常工作,它引入了许多“互操作”改进和新功能

> system('bash -c "ls /"')

生成:

bin   cache  dev  home  lib    media  opt   root  sbin  srv  tmp  var
boot  data   etc  init  lib64  mnt    proc  run   snap  sys  usr
于 2017-01-04T22:30:41.407 回答