Skip to content

Instantly share code, notes, and snippets.

@Gordin
Last active May 1, 2024 14:32
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Gordin/67c9f5e995f4b625adf485eb791dea3e to your computer and use it in GitHub Desktop.
Save Gordin/67c9f5e995f4b625adf485eb791dea3e to your computer and use it in GitHub Desktop.
If you put this in your .bashrc/.zshrc you will be able to use cd to Windows style paths. This is probably only useful for WSL users.
cd() {
# Check if no arguments to make just typing cd<Enter> work
# Also check if the first argument starts with a - and let cd handle it
if [ $# -eq 0 ] || [[ $1 == -* ]]
then
builtin cd $@
return
fi
# If path exists, just cd into it
# (also, using $* and not $@ makes it so you don't have to escape spaces any more)
if [[ -d "$*" ]]
then
builtin cd "$*"
return
else
# Try converting from Windows to absolute Linux path and try again
WSLP=$(wslpath -ua "$*")
if [[ -d "$WSLP" ]]
then
builtin cd "$WSLP"
return
fi
fi
# If both options don't work, just let the builtin cd handle it
builtin cd "$*"
}
@saravana815
Copy link

Thanks

@dufferzafar
Copy link

This needs to be updated to support cd enhancing tools like https://github.com/rupa/z or https://github.com/skywind3000/z.lua

@Gordin
Copy link
Author

Gordin commented Mar 16, 2021

This needs to be updated to support cd enhancing tools like https://github.com/rupa/z or https://github.com/skywind3000/z.lua

@dufferzafar I don't use these tools, but I would guess that you could just replace all instances of cd (including the function name in line 1) with z and it could work? 🤔

@morphykuffour
Copy link

morphykuffour commented Nov 17, 2021

Is there a way to use this function when CDing into windows directories where you don't have to surround the path with quotes. This is what I mean:
\# works but you need quotes on first argument
\# cdw() { cd $(wslpath "$1"); }

\# Your Function does not support this functionality.

\# In bash shell
cdw C:\tmp
\#causes an error

@Gordin
Copy link
Author

Gordin commented Dec 17, 2021

@morphykuffour Probably not. The problem with Windows paths is that they contain \, which will probably lead to your terminal thinking parts of the path are actually escape sequences. Because this happens before the command is actually called, you can't really do anything about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment