简体   繁体   中英

How to translate a Windows path for Windows Subsystem for Linux

I'm looking for a way to translate Win32 paths into POSIX paths, preferably using Win32 tools.

Background :

The latest Windows 10 Insider Build introduced the Windows Subsystem for Linux (WSL) including a native bash provided by Canonical, the company behind Ubuntu. Their implementation of bash goes by the rather complicated name of Bash on Ubuntu on Windows , which I will refer to as bash.exe in the following.

The equivalent of accessing the Windows path C:\\Users\\me\\Desktop in bash.exe is /mnt/c/Users/me/Desktop .

I'm trying to pass a path to bash.exe from the Windows Command Prompt (eg bash -c ls /mnt/me/Desktop ). Since that requires me to pass a POSIX path, I was wondering if Microsoft offers any tools to translate Win32 paths programmatically into POSIX paths (like cygpath does in Cygwin.)

Unless Windows ships with any tools for translation, I'm open to alternatives to determine the path, eg using Node or Python.

I have written a small shell script at [0] which is a beginning and I want to improve over time. I guess "sed" is a good tool to do some string replacements.

Here the current status:

linuxify() {
    windowspath=$1
    temppath="$(echo $windowspath | sed -E 's/([A-Z]):/\/mnt\/\L\1/g')"  # C: -> /mnt/c, E: -> /mnt/e
    temppath="$(echo $temppath | sed 's/\\/\//g')"  # backslash -> forward slash
    linuxpath=$temppath
    echo $linuxpath
}

Then you can use it like this

cd "`linuxify "E:\Marvin Kastner\Documents\Uni\Master\gitrepos\masterarbeit_neu"`"

[0] https://gist.github.com/1kastner/723a52f352c3eead42988c26b4ade5d0

It turns out that NodeJS has a built-in module for this kind of stuff, called path . Although it doesn't completely fix the issue at hand, it's a valid workaround (to me). Just require("path") and decide on the block or one liner.

Here's the block:

var p = require("path")
var path = "C:\\Users\\me\\Desktop"
var sepa = path.split(p.win32.sep)
var newS = [].concat([sepa[0].toLowerCase()], sepa.slice(1))
var newP = "/mnt/" + p.posix.join.apply(p.posix, newS).replace(":", "")
// newP == "/mnt/c/Users/me/Desktop

As a one liner:

var p = require("path")
var d = "/mnt/" + p.posix.join.apply(p.posix, [].concat(["C:\\Users\\me\\Desktop".split(p.win32.sep)[0].toLowerCase()], "F:\\Users\\me\\Desktop".split(p.win32.sep).slice(1))).replace(":", "")

Windows子系统中Ubuntu位置的路径位于:

C:\Users\<user>\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM