WSL: Enhance the cd Command to Handle Windows Paths

WSL: Enhance the cd Command to Handle Windows Paths

You can use a function to augment the cd command in Windows Subsystem for Linux (WSL) shells to convert Windows directory paths to Unix paths automatically.

In a shell, I often want to use the Windows file path on the clipboard, but that path is in Windows format (such as C:\Program Files\Microsoft Office) rather than Unix format (such as /mnt/c/Program Files/Microsoft Office). I can use the wslpath command to convert from one format to the other, but this is a hassle to remember and backquote, where quoting for the spaces and backslashes in Windows paths is enough of a hassle already.

Incidentally, WSL makes me miss 8.3 filenames, or at least, file names without spaces. It would be nice if there was a setting in Windows to force 8.3 names, but instead Windows apparently does not even generate shadow 8.3 names by default anymore. But I digress. Let’s not get even started on the wisdom of Microsoft’s decision to use backslash characters as the delimiters in file paths.

Anyway, below is the function that I add to my ~/.bashrc file to address this and an alias to override the cd command to use that function. If there are no command line arguments or if there is more than one command line argument, the function calls cd to switch to the home directory or generate an error message, accordingly. Otherwise, there is exactly one command line argument; if it contains a backslash, then convert it to a Unix path. Then move to that directory, following symbolic links to their sources.

function wcd()

 if [ "$#" -ne 1 ]  

 then 

  cd $@

 elif [[ "$1" =~ "\\" ]]

 then

  path=`wslpath "$1"`

  cd `realpath "$path"`

 else

  cd `realpath "$1"`

 fi

}

alias cd=wcd

I am not sure if it is from this, but the shell sometimes hangs if I source .bashrc interactively after the shell has applied it at login.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了