Sunday, October 22, 2017

How to open your browser from bash on Windows (WSL), GNU/Linux, macOS and Solaris

Sometimes it can be useful to open a browser from your bash. I have developed a bash function that does exactly that - and since I am a fan of multiple operating systems - the function works not only on GNU/Linux, macOS, and Solaris but also on the bash on Windows as part of the WSL (Windows Subsystem for Linux).

function openBrowser() {
  OS=$(uname -s)
  case "$OS" in
          open "$URL"
          if [[ "$(cat /proc/sys/kernel/osrelease)" =~ "Microsoft" ]]; then
              # We are in bash on WSL (Windows Subsystem for Linux)
              # We don't need a Linux-Browser and an X-Server,
              # we just can call iexplore.exe,
              # see also
              if [[ "(uname -p)" == "x86_64" ]]; then
                  /mnt/c/Program\ Files/Internet\ Explorer/iexplore.exe "$URL" 2> /dev/null
                  /mnt/c/Program\ Files\ \(x86\)/Internet\ Explorer/iexplore.exe "$URL" 2> /dev/null
              xdg-open "$URL"
          /usr/dt/bin/sdtwebclient "$URL"
          printf "Not supported on %s\n" "$OS"

To use the function in your bash-script, simply source the file that contains the function - I called the file network.include. You find the file as well at the repository of my tiny project called bashberries - that is a tiny collection of both bash scripts and bash includes, released under the terms of the Apache 2.0 license. The script below calls the function from above and opens the homepage to bashberries:

#!/usr/bin/env bash
. ./network.include

Best regards,

Update Oct 23, 2017:
uname -r is not reliable enough, it does not work on the wls beta with Ubuntu 14.04 for example, better is to do a cat /proc/sys/kernel/osrelease

Update Oct 23, 2017:
bash-dwarfs has been renamed to bashberries.