nicoulaj nicoulaj - 1 year ago 81
Bash Question

Clean way to launch the web browser from shell script?

In a bash script, I need to launch the user web browser. There seems to be many ways of doing this:


  • xdg-open

  • gnome-open
    on GNOME

  • www-browser

  • x-www-browser

  • ...

Is there a more-standard-than-the-others way to do this that would work on most platforms, or should I just go with something like this:

#/usr/bin/env bash

if [ -n $BROWSER ]; then
elif which xdg-open > /dev/null; then
xdg-open ''
elif which gnome-open > /dev/null; then
gnome-open ''
# elif bla bla bla...
echo "Could not detect the web browser to use."

Answer Source

xdg-open is standardized and should be available in most distributions.


  1. eval is evil, don't use it.
  2. Quote your variables.
  3. Use the correct test operators in the correct way.

Here is an example:

if which xdg-open > /dev/null
  xdg-open URL
elif which gnome-open > /dev/null
  gnome-open URL

Maybe this version is slightly better (still untested):

[[ -x $BROWSER ]] && exec "$BROWSER" "$URL"
path=$(which xdg-open || which gnome-open) && exec "$path" "$URL"
echo "Can't find browser"