Skip to content

标题: 在WSL中切换Windows/Linux路径表达方式

https://scz.617.cn/windows/202206120354.txt

Q:

When we use WSL shell on windows, it is annoying to convert the path back and forth, is it possible to make our life easier?

A: bluerust 2022-06-12

WSL provides a tool named wslpath, which can help convert the paths between Windows and Linux, the usage is very simple:

wslpath ''

The quotes are necessary to avoid escaping the path when it is Windows format.

By virtue of this tool, we can add the following code to .bashrc:


function _pushd () { local _path="${1}"

if [[ "${_path}" = *"\\"* ]] ; then
    _path=$(wslpath -u "${_path}")
fi
builtin pushd "${_path}"

}

function _cd () { local _path="${1}"

if [[ "${_path}" = *"\\"* ]] ; then
    _path=$(wslpath -u "${_path}")
fi
builtin cd "${_path}"

}

pushd 'C:\Program Files (x86)\Google'

cd 'C:\Program Files (x86)\Google'

the path must be quoted with either double quotes or single quote

alias pushd='_pushd' alias cd='_cd'


After updating the rc file, we need to source it:

source ~/.bashrc

Now, you can use the Windows path with cd and pushd commands:

pushd 'C:\Program Files (x86)\Google' cd 'C:\Program Files (x86)\Google'

Please keep in mind that, if you omit the slash following the colon sign, wslpath would treat it as a directory name, for instance:

$ wslpath -a x: /mnt/c/x: