Sample Header Ad - 728x90

How do I make WSL2's cd command accept windows paths?

5 votes
4 answers
1714 views
I'm a WSL convert, coming from cygwin. One of the neat things cygwin does is accept unix *and* Windows file paths in the cd command. Of course, most Windows paths contain \, which is a special character in unix, but so long as you escape it, cding to Windows paths works as expected: cd 'C:\Program Files' will *C*hange your *D*irectory to /cygdrive/c/Program Files1. This isn't the case for WSL. cd 'C:\Program Files' prints an error message: cd: no such file or directory: C:\Program Files. I like the cygwin functionality. **Is there a way of getting the same behavior when I use cd in WSL?** The solution could come in the form of installing a 3rd party tool (i.e., sudo apt install ), creating an alias, enabling some bind or bindkey in my shell, or writing my own shell script. So long as it allows me to use unix *and* Windows paths as a cd argument, I'll be happy. --- ### Additional information My distro is Ubuntu. I use zsh as my main shell but write shell scripts in bash. Ideally, the solution would work for both, but if that's not possible, I'd want a zsh solution. I found this related question that may help people trying to answer mine: https://unix.stackexchange.com/questions/174182/cygwin-cd-to-windows-paths-easily For those that don't use WSL but would like to help, it's worth knowing that WSL comes with a command named wslpath. This is the closest thing I've found to official documentation , and this is its usage output:
➜  ~ wslpath
wslpath: Invalid argument
Usage:
    -a    force result to absolute path format
    -u    translate from a Windows path to a WSL path (default)
    -w    translate from a WSL path to a Windows path
    -m    translate from a WSL path to a Windows path, with '/' instead of '\'

EX: wslpath 'c:\users'
I'm already using this command in another script I wrote to open a directory/file in Windows from the WSL command line:
➜  ~ cat ~/bin/open
#! /bin/bash
set -x

arg="$*"
explorer.exe "$(wslpath -w "$arg")" # take a unix path and open it in Windows
1: cygwin's /cygdrive/c/ path is synonymous with WSL's /mnt/c path.
Asked by Daniel Kaplan (1070 rep)
Dec 21, 2023, 01:48 AM
Last activity: Apr 5, 2024, 12:47 AM