Home > Back-end >  Opening directory in file explorer from WSL2
Opening directory in file explorer from WSL2

Time:10-04

Im in windows terminal and I would like to open directories in file explorer, while in WSL2 Ubuntu.

I tried typing "explorer.exe Desktop/", but it opens Documents, in fact every time I try to run it, it just opens Documents, except when I type "explorer.exe .", then it opens the current directory correctly, but I want it to work with any directory I give it. Any ideas?

Edit 1: I found this function, just add it to your ~/.bashrc and it works

start(){
    path=$(wslpath -w "$1")
    /mnt/c/Windows/explorer.exe "$path"
}

Type start "Some Path" without quotation marks and it opens the path in file explorer, also I saw that I needed to add quotation marks around argument of explorer.exe

CodePudding user response:

"Desktop/" doesn't actually resolve to a folder. Try the following:

explorer.exe "c:\users\<YOUR USERNAME>\Desktop"

This provides the full (absolute) path to explorer.exe.

CodePudding user response:

Answer is in post, but I will type it here again. Put this function in your ~/.bashrc

start(){
    path=$(wslpath -w "$1")
    /mnt/c/Windows/explorer.exe "$path"
}

Now when you type start "Some Path" you will open it in file explorer. You can also remove /mnt/c/Windows/ from /mnt/c/Windows/explorer.exe if you want.

PTH (Path to here): Basically what my problem was that I was trying to read user input for the path to recreate the start command from cmd and powershell, but in wsl2 that was a lot harder because it doesn't have GUI so it doesn't know how to open it using xdg-open or other tools. Using read command from bash was not good enough because of the newline it always gives the user to type, but this uses arguments and takes the next thing you type in bash instantly which is awesome. Functions in bash work with arguments like lets say programs in c where you type ./program arg1 arg2 arg3..., where in bash it is the same, the number indicating the argument, so $0 is the zero-th argument which is always the name, so we don't use it. Starting from $1 $2 $3 and so on are the arguments which are usable in bash functions. In our case typing "start Desktop/", $1 is assigned "Desktop/", which is then converted to C:\Users<Your Username>\Desktop and assigned to $path. Then $path is passed to /mnt/c/Windows/explorer.exe to finally open in file explorer. Pretty nifty right? That's what I said first time 1 minute ago when I first saw and understood bash functions.

  • Related