WSL (Ubuntu): how to open localhost in browser from bash terminal - windows

I am trying to open http://localhost in (any) browser from WSL bash terminal.
So far I have tried:
How can I open Google Chrome from the terminal with the URL "localhost:3000"?
"Couldn't find a file descriptor referring to the console" on Ubuntu bash on Windows
How to mention C:\Program Files in batchfile
No luck in setting up BROWSER variable for xdg-open, it responds to xdg-open http://localhost with /usr/bin/xdg-open: 851: /usr/bin/xdg-open: /c/"Program: not found.
I have tried escaping with \ and ^. Using %ProgramFiles(x86)% and ofcorse "Program Files (x86)". More or less it is the same answer every time... Any ideas how to set a work flow for opening browser in WSL?
So far I've ended up with:
/c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe localhost
But I am looking for more elegant solution.

You can invoke the Windows command line from Bash and use Windows file association to open URL with the default Windows browser.
To do so just type in Bash:
cmd.exe /C start http://localhost
In my case this loads localhost in Chrome, note that the full URL is necessary for Windows to decide what to do.
This is similar to what open does in MacOS, hence you may find useful to directly alias the command and use it also for other type of files:
# add this to .bash_aliases
open='cmd.exe /C start'
Now you can open URL or open file.pdf directly from WSL.
Note: since you are simply redirecting commands to cmd.exe, it needs to have access to the file your working with. As a consequence the above solution will work when you find yourself in the Windows file system, but probably will fail when you are working with files in Linux partition (i.e. in the tmp or in the bin folder). This probably has been fixed in the new version of the WSL but I have not tested it.

You are almost there. Just add an alias for the windows chrome executable
http://www.linfo.org/alias.html
alias chrome="/c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe"
Now you can simply run chrome localhost and open chrome in any web location you desire.

To open localhost in browser from bash terminal, you need to configure wsl so that it defaults to whatever browser has been set as default in your windows 10 system.
You can do this by using some tools from wslu ("A collection of utilities for WSL").
For this purpose you need.
wslview (-u, --unregister "remove wslview as the default WSL web browser.
-r, --register "register wslview as the default WSL web browser.)
wslpath (-a "force result to absolute path format",
-u "translate from a Windows path to a WSL path (default)")
You need to register your preferred browsers like this...
For Google Chrome:
wslview -r $(wslpath -au 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
For Microsoft Edge:
wslview -r $(wslpath -au 'C:\Windows\SystemApps\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\MicrosoftEdge.exe')
Now you can open localhost as x-www-browser localhost:8080 or www-browser localhost:8080 and x-www-browser or www-browser will default to whatever is your current windows 10 default browser provided it has been registered as described above.
Do not forget to indicate the port; localhost alone did not work for me.
To unregister any browser just change the -r flag to -u.
Have a look at wslview help: info wslview <enter> in the wsl terminal
and wslpath <enter> for help with wslpath.

Install wslu (A collection of utilities for WSL) https://github.com/wslutilities/wslu#feature and then add these two lines to your shell's RC file, e.g. .bashrc or .zshrc.
export DISPLAY=:0
export BROWSER=/usr/bin/wslview

You can set the BROWSER variable as you have done . But xdg-open won't work in WSL as the
xdg-openscripts are setup to work with unquoted environment variables ( in which case ,
the path breaks due to spaces in the pathname ).
You can use the wsl-opennpm utility to do the same for WSL .
Once you have npm installed , install wsl-open utility :
sudo npm install -g wsl-open
To open any URL with default Windows Browser :
wsl-open http://google.com
You can also set wsl-open as default program for a file type in WSL :
wsl-open -w // sets wsl-open as the Shell Browser
Then you can use the standard xdg-open for URLs as well with default windows browser :
xdg-open http://google.com

I created a script that basically forwards xdg-open to powershell -c start
Not tested much though.
sudo tee /usr/local/bin/xdg-open <<EOF
#!/bin/sh
powershell.exe -c start "'\$#'"
EOF
sudo chmod +x /usr/local/bin/xdg-open
Cheers
Oliver

Came across this article that worked for me:
https://towardsdatascience.com/running-jupyter-notebook-on-wsl-while-using-firefox-on-windows-5a47ebfae4c1
In short:
Step 1 - Generate config for Jupyter Notebook:
jupyter notebook --generate-config
Step 2 - Edit the config file using "nano" or other editor
The config fileshould be under your home directory under ".jupyter" folder:
~/.jupyter/jupyter_notebook_config.py
Step 3 - Disable launching browser by redirecting file
First comment out the line, then change True to False:
c.NotebookApp.use_redirect_file = False
Step 4 - add a line to your .bashrc file to set the BROWSER path
export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'
For me it was Chrome under my Windows Program File. Otherwise any linux installation under WSL doesn't have a native browser to launch, so need to set it to the Windows executable.
Step 5 - restart .bashrc
source .bashrc
That should work!

https://github.com/microsoft/WSL/issues/3632#issuecomment-690061348
export BROWSER='eval "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"'
xdg-open https://google.com # nice work
solved the spaced path problem.
it worked for me.

Now you can simple use :
sensible-browser http://www.google.com
it already comes with wsl and it opens the default browser in windows
ps: you can also use wslview . to open the file explorer from the bash terminal

i'll give you a suggestion, it could be opened via visual studio code in wsl. And install the live server plugin.

Ok so first of all, I don't use windows anymore so I can't post a full solution that I've personally tested, but back when I did use windows, I use to do this and it worked. (This should probably be a comment, but a while back I deleted some unaccepted answers and lot the associated reputation :/)
Solution:
Don't try to launch your windows programs from inside WSL, instead install the linux version of the program and an X server, such as Xming. Here is an example tutorial for forwarding X apps back to Xming on windows.
Summarized, install Xming (on Windows). Then export the DISPLAY variable:
export DISPLAY=:0
Install google-chrome inside WSL and launch it via the CLI. It should show up on your desktop.
Note: There's also a way to use PuTTY alongside XMing for remote viewing, but you'll need to disable Windows firewalls and install the full openssh-server inside WSL first.

Related

Start WSL Ubuntu in specific or current folder on Windows

When installing Subsystem for Linux and Ubuntu from store on his development machine I can switch (or start) to Ubuntu shell by simply
But the Ubuntu shell start in /home/techsupp folder by default. Is it possible to force it to start in same folder than the one I use my Ubuntu command?
So in my example I should be in
/mnt/h
Thank you.
What I already tried:
H:\>ubuntu help
Launches or configures a linux distribution.
Usage:
<no args>
- Launches the distro's default behavior. By default, this launches your default shell.
run <command line>
- Run the given command line in that distro, using the default configuration.
- Everything after `run ` is passed to the linux LaunchProcess call.
config [setting [value]]
- Configure certain settings for this distro.
- Settings are any of the following (by default)
- `--default-user <username>`: Set the default user for this distro to <username>
clean
- Uninstalls the distro. The appx remains on your machine. This can be
useful for "factory resetting" your instance. This removes the linux
filesystem from the disk, but not the app from your PC, so you don't
need to redownload the entire tar.gz again.
help
- Print this usage message.
I also discover this request on uservoice: https://wpdev.uservoice.com/forums/266908-command-prompt-console-windows-subsystem-for-l/suggestions/13421103-let-us-right-click-open-bash-here-from-explorer?tracking_code=8a8bc624c72a8336565fcd6d5737d712
Please vote for it.
I'm on Windows 10 Home with May Update and have Ubuntu 18.04 for WSL installed, I can open the console in any folder with Shift + Right Click and selecting the Open Linux shell here option
If you check in Task Manager how the explorer "Open Linux shell here" option opens wsl, you can see that there's a "--cd" option.
ubuntu run
run <command line>
Run the provided command line in the current working directory. If no
command line is provided, the default shell is launched.
As far as I can tell the effect is the same as running ubuntu, except that it starts in the current directory.
This command works even as a right click open here command in explorer. Adapting from this article:
RegEdit to HKEY_CLASSES_ROOT\Directory\Background\shell and create a new key
edit (Default) to "Open Ubuntu here" or similar.
add a key named command
edit (Default) to ubuntu run
Now you have a functional "Open Ubuntu here" right click menu in explorer.
The problem I have with wsl is that the wsl bash window doesn't have the Ubuntu icon, even if it starts the Ubuntu distribution.
If you use wsl.exe, it will start WSL in current directory. But the difference between wsl and ubuntu is that if you have installed two or more distros (e,g, Ubuntu and Fedora), the default one will get started. You can set the default to Ubuntu by running wslconfig /setdefault Ubuntu.
Reference: [1] https://learn.microsoft.com/en-us/windows/wsl/wsl-config
seems that there is a very simpel solution.
just add the following in Ubuntu configuration in the profiles.json file
"commandline": "wsl ~ -d Ubuntu",
The method that has worked for me is to use the Windows Terminal app and configure it to start in the desired location.
Example based on WSL2 and Ubuntu 20.04:
settings.json - Add this line to "Ubuntu-20.04" section:
"startingDirectory": "//wsl$/Ubuntu-20.04/home/<username>/"
Change <username> to be the name of the user you created on install of Ubuntu 20.04.
Step 1: Install Windows Terminal
Step 2: Go to the folder you want to open Ubuntu in and open Windows Terminal by right-clicking.
Step 3: Go to Windows Terminal Settings and navigate to your Linux distro (in my case Ubuntu 20.04) and check this option.
Now every time you open Ubuntu through the Windows terminal it will open in that directory.
Modern solution
Install windows terminal , from Microsoft store
Go on settings
Once you have ubuntu installed you will see it on the list of profiles and then click on open json
Open cmd , type wsl , type cd, type pwdwslc then copy the path [!
And put it in the json file, on ubuntu profile, startingDirectory
Note: I have used linux home directory as default directory used by ubuntu. So if you feel like you have other directory you want to use you can replace it with /home/claranceliberi to your own prefereble directory
with this little script you can execute every command from the directory your Powershell is currently in. It only works if the drive is already mounted to /mnt/ in the subsystem. It doesn't work with network resources.
function tux {$dl = (pwd).Path | wsl eval "cut -c 1 | tr 'A-Z' 'a-z'"; $wd = (pwd).Path | wsl eval "cut -d : -f 2 | tr '\\' '/' 2> /dev/null" ; wsl eval "cd '/mnt/$dl$wd' && eval '$args'"}
after you have executed it, you can use it like this:
tux vim test.txt
First, you have to check whether wsl is using ubuntu as default or not.
For me it was not. Write the below command on cmd:
wsl -l
Like this
If not then Write wsl -s Ubuntu-20.04 to set it as default.
Now you can run ubuntu bash from any directory by doing shift + Rightclick as shown Here.
if your default terminal is Ubuntu, then you can open Ubuntu in the current dir easily.
Go to the address bar of the file explorer by clicking on it
or you can use keyboard shortcut alt+d and
there type
wt -d .
and if the default is Ubuntu, it will open Ubuntu on that path or you can also type
ubuntu run
and it doesn't matter if the default terminal is Ubuntu or not, it will open ubuntu there regardless of anything.

How to open the current directory on Bash on Windows?

I know that in MacOS, people use the open . command to open the current directory in a file manager.
Does anybody know the appropriate command to do the same task in Bash on Windows?
On Windows with Git Bash, just type:
start .
it will open the current directory in the file explorer.
You can now call explorer.exe from the bash subsystem. I've set up an alias to use it. I've added the copy to clipboard alias as well for good measure.
Alias:
alias open="explorer.exe"
alias pbcopy="clip.exe"
Example:
cat ~/.ssh/id_rsa.pub | pbcopy
open .
open "D:\\Dir"
The open alias plays well with ., but you'll need to pass it the Windows path if you want to specify a directory.
Right now Microsoft don't recommend to mix Windows explorer with the bash shell. In latest win10 Insider builds you could use from bash something like this
cmd.exe /c start .
If you are using Win10 Anniversary Edition you could try installing a Desktop Environment. Start reading this
https://github.com/microsoft/bashonwindows/issues/637
After that you could open a window with the present folder content with
gnome-open .
I'm using this function:
open()
{
explorer.exe `wslpath -w "$1"`
}
So if you are in /mnt/c/Users/ and would like to open that folder, just type open .
wslpath will resolve only paths from the Windows system, be aware. If you are looking to do something like open ~ it will not work, and you will get:
wslpath: /home/my-user: Result not representable
Command usage
wslpath 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’
A proof that this works:
You Can Use the following command: explorer .
I have added
alias open='explorer.exe `wslpath -w "$1"`'
to the .bashrc file
opens current folder when typed open
I'm using windows ubuntu subsystem.
This command should do it:
$ explorer
try this
$ explorer .
This will work on bash command in windows. I was using R studio and was able to open the directory.
If start . doesn't work for you, it's essentially the same as running explorer.exe . so you can create an alias for it which is what I did.
alias start="explorer.exe"
Side note: Another useful one to have is BROWSER. explorer.exe is capable of starting your default web browser. This comes in handy when you run scripts that open a web browser like starting a React.js development server.
export BROWSER="explorer.exe"
start . - this is the equivalent of open . in bash
To work in all type of paths (Windows-Style and Linux-Style), do as following (the answer of mine to my own question on SU):
(Here my challenge was how I could open Explorer in current working directory with Linux-Style path for view purposes, if you are going into modification or do something else other than just viewing, this is at your own risk, please also read Do not change Linux files using Windows apps and tools):
explorer.exe "C:\Users\userNmae\AppData\Local\Lxss$(sed 's:/:\\:g' <<<"$PWD")"
this will open the Explorer exactly in your working directory. The only thing you need is now define a function to get it to work. You can add this into your .bashrc and source it or re-open Bash.
xplor(){
explorer.exe "C:\Users\userName\AppData\Local\Lxss$(sed 's:/:\\:g' <<<"$PWD")";
}
Note: Replace userName with your Windows User account name there.
In WSL2 it looks like the open command is now doing what start does in Windows command. I just put an alias in my .bashrc
start="open"
Now you can do either start . or open . depending on your preferences.
Using the MINGW64 shell that comes with Git for Windows, I created these functions in my .profile:
function towinpath {
{ cd "$1" && pwd -W; } | sed 's|/|\\|g'
}
function open {
path_to_open=""
if [ -f "$1" ]; then
filename=$(basename "$1")
win_dirname=$(towinpath "$(dirname "$1")")
path_to_open="$win_dirname\\$filename"
elif [ -d "$1" ]; then
path_to_open=$(towinpath "$1")
else
# Take our chances with windows explorer ...
path_to_open="$1"
fi
if [ -z "$path_to_open" ]; then
echo "Failed to open $1"
else
explorer "$path_to_open"
fi
}
This seems to work with just about everything you can throw at Windows File Explorer:
open . # Opens the current directory
open ../ # Opens the directory above this one
open /c/Windows # Opens C:\Windows
open ~/AppData # Opens my AppData folder
open ~/*.csv # Opens the first CSV file in my home directory in Excel
open https://stackoverflow.com # Opens StackOverflow in my browser!
# Opens paths with spaces in them too:
open /c/Program\ Files/Sublime\ Text\ 3/sublime_text.exe
open '/c/Program Files/Sublime Text 3/sublime_text.exe'
To open the current directory via windows subsystem for linux (WSL) use :
$ explorer.exe .
The easiest way is to edit .bash_aliases
nano ~/.bash_aliases
# add
alias open='explorer.exe $1'
# save and close: cltr-s, cltr-x
source ~/.bash_aliases
Now, we can use: open . or open documents
Opening Windows Terminal in a directory and typing start bash will open a bash terminal in that directory.

Emacs can't start server

I try to start emacs server on a Windows 8 machine. I downloaded vanilla emacs, and run it using runemacs.exe. Then I run M-x server-start and the execution of this command takes about 3 minutes, after that there's a ~/.emacs.d/server/server file with the following contents:
127.0.0.1:65118 5868
r#Twzr]X-VjCB`g\&t;U1<bj3X]}6!8XUz~P;{q9'AIj322!w0O1XK[/K4v>ZOK*
and emacs server doesn't run: when I try to open a file with emacsclientw.exe it says no server.
Apparently emacs tried to start a server but failed. I'm the owner of the ~/.emacs.d folder.
You're using a non-standard socket directory. By default, the sockets are stored in /tmp/emacsXYZQ (where XYZQ is a number). emacsclient cannot be expected to know where you put the sockets, so you need to tell it (if it's not the usual place). You can do this with the -s command.
emacsclient -s ~/.emacs.d/server/server
Normally, you'd make this more convienient by adding
EMACS_SERVER_FILE=~/.emacs.d/server/server
to your ~/.profile and using emacsclient normally, but I'm not sure what the windows analog of that would be.
references:
this SO question
emacsclient options docs

What file explorer can I use in Cygwin with UNIX like paths?

I'm fed up with using Windows Explorer as my file browser as I use
Cygwin bash as my primary command line environment.
Windows Explorer shows the full path in the address bar.
Usually, I copy that, pasting it to the cygwin command prompt as in
cygpath ""
I then copy paste the output of cygpath so I can
cd to it. I've also set up cpath "Bash Shell Here"
but this only works on right clicking directories.
I've used WinSCP via SSH.
ie. Start an SSH daemon in cygwin and connect to it via WinSCP.
What file explorer can I use in Cygwin with UNIX like paths?
Is there a cygwin X Windows file explorer?
Have you tried Midnight Commander (mc)? It's in the Cygwin package repository.
If you surround the path from Windows Explorer with single or double quotes, there is no need to use the cygpath command.
In regard to your quest for a compatible file manager, I've heard that KDE's Konqueror runs on Windows.

Open a file from Cygwin

Is there an equivalent to OSX open command in cygwin. open opens a file with the default application for that type.
I want to do something like
$ magic-command file.xls
#excel opens as if file.xls would have been double-clicked
$ magic-command file.txt
#notepad opens as if file.txt would have been double-clicked
You get the idea?
Basically something like a "cygwin-double-click" command.
You can also use the cygwin utility:
cygstart <your file>
To make things OSX-like add the following to your bashrc
alias open='cygstart'
Don't forget to check out the man page for cygstart.
You can use the start command from the CMD like this:
cmd /c start <your file>
explorer <your file>
works too. What is nice is
explorer .
opens a windows explorer window in the current directory. But then
cygstart .
does the same thing and does more, but I find 'explorer' slightly easier to remember.
I am using Cygwin in Win7. I can run file on windows through ccygwin command line.
cygstart <your file>
when you run this command your file will open in windows.
Under the Windows command-line interpreter (cmd.exe) there is support for the start command. I know of somebody who implemented start in cygwin. You can find the page about it here.
You could also simply call cmd.exe (usually located in /cygdrive/c/windows/system32/cmd.exe) with the following arguments cmd /c "start yourfile.file"
If, like me, you are using putty to ssh locally on your windows machine to Cygwin as cmd.exe is a terrible console, you may want to change your sshd service to allow it to access the local desktop (this will only work on certain windows flavors) under the sshd windows service Logon properties.
Yes, there is an equivalent to Windows, try with xdg-open <your file>

Resources