Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute linux commands from R via bash under the Windows Subsystem for Linux (WSL)?

The WSL on Windows 10 allows execution of Linux commands and command-line tools via bash.exe. Very usefully, a Linux tool/command can be called from the Windows command-line (cmd.exe) by passing it as an argument to bash.exe like so:

bash.exe -c <linux command>

This is very useful because it should allow Windows-based scripts to combine Windows and Linux tools seamlessly.

Unfortunately, I have failed to call Linux commands from an R script (see below).

0) System

Win10 x64 + Anniversary Update + WSL installed

1) Comparison cases where calling Linux commands work

The following all work for me; shown here just with an example call to ls.

  • from the windows command-line (cmd.exe prompt)

    bash -c "ls /mnt/a"
    

    bash -c "ls /mnt/a > /mnt/a/test.txt"
    
  • Same works if started from WinKey + R

  • Same works from within a .bat file.

  • It can be called from compiled code. I tried with Delphi XE2 32-bit and 64-bit using ShellExecute:

    For example, these work (32 and 64 bit):

    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);
    

    Or (32-bit code):

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

    Or (64-bit code):

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

    All of these seem to work (and ShellExecute returns 42).

2) Failure to call Linux commands from R using R 3.3.1 x64

All of the below (and several similar things I've tried) fail with status 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) Question

Given that examples under 1) work, I find 2) very puzzling. Am I missing anything obvious here?

I would be very grateful for a simple example where running a Linux command via bash.exe under WSL works.

like image 613
PhiS Avatar asked Aug 07 '16 21:08

PhiS


1 Answers

Your failing examples should now be working correctly in Windows 10 Insider builds >= 14951 which introduced many "interop" improvements and new capabilities:

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

Generates:

bin   cache  dev  home  lib    media  opt   root  sbin  srv  tmp  var
boot  data   etc  init  lib64  mnt    proc  run   snap  sys  usr
like image 191
Rich Turner Avatar answered Oct 28 '22 23:10

Rich Turner