A clean way to launch a web browser from a shell script?

In a bash script, I need to run the user's web browser. There seem to be many ways to do this:

  • $BROWSER
  • xdg-open
  • gnome-open on GNOME
  • www-browser
  • x-www-browser
  • ...

Is there a way more than others to work on most platforms, or do I just need to go with something like this:

 #/usr/bin/env bash if [ -n $BROWSER ]; then $BROWSER 'http://wwww.google.com' elif which xdg-open > /dev/null; then xdg-open 'http://wwww.google.com' elif which gnome-open > /dev/null; then gnome-open 'http://wwww.google.com' # elif bla bla bla... else echo "Could not detect the web browser to use." fi 
+89
command-line standards bash shell
Jun 26 '10 at 16:15
source share
5 answers

xdg-open standardized and should be available on most distributions.

Otherwise:

  • eval is evil, do not use it.
  • Enter your variables.
  • Use the correct test statements correctly.

Here is an example:

 #!/bin/bash if which xdg-open > /dev/null then xdg-open URL elif which gnome-open > /dev/null then gnome-open URL fi 

Perhaps this version is slightly better (not yet tested):

 #!/bin/bash URL=$1 [[ -x $BROWSER ]] && exec "$BROWSER" "$URL" path=$(which xdg-open || which gnome-open) && exec "$path" "$URL" echo "Can't find browser" 
+64
Jun 26 '10 at 16:51
source share
 python -mwebbrowser http://example.com 

works on many platforms

+89
Jun 26 '10 at 17:11
source share

OSX:

 $ open -a /Applications/Safari.app http://www.google.com 

or

 $ open -a /Applications/Firefox.app http://www.google.com 

or simply...

 $ open some_url 
+51
Jun 01 '12 at 18:43
source share

You can use the following:

 x-www-browser 

It will not start the user, but rather will be the default X browser.

See: this stream.

+12
Jun 26 2018-10-06T00:
source share

This may not match exactly what you want to do, but there is a very simple way to create and start a server using the npm http-server package .

After installation (just npm install http-server -g ) you can put

http-server -o

in a bash script and it will start the server from the current directory and open a browser on this page.

-6
Jul 15 '16 at 18:21
source share



All Articles