Scripting

Choose Browser

Bash script to decide browser based on string matches in URLs?

I wrote this because I use firefox mainly, but I use chromium for hangouts. If somebody sends me a link in, for example, pidgin, I want it to open in firefox unless it is a google plus link.

Thus, this script is set up as my 'default' user browser (or you could just set it in pidgin prefs).

You can edit your prefererred browsers, alternate browsers (for when a string matches) and matching strings (they are all space separated for multiple entries)


#!/usr/bin/env bash

URL_TO_MATCH="$@"
if [ -z "$1" ]; then
  echo "I can't match if you don't give me a param....."
  exit 1
fi

PREF_BROWSER="firefox"
ALT_BROWSER="chromium chromium-browser chrome"

ALT_BROWSER_MATCHES="plus.google.com"

function locate_progs {
  for name in $1; do
    local POSS=$(which $name 2>/dev/null)
    if [ -n "$POSS" ];then
      echo $POSS
      return 0
    fi
  done
  echo "cannot find any one of: $1"
  exit 1
}

function use_alt {
  for possmatch in $ALT_BROWSER_MATCHES; do
    local POSS=$(echo "$URL_TO_MATCH" |grep "$possmatch" )
    echo $POSS
    if [ -n "$POSS" ]; then
      $("$LOCATED_ALT" "$URL_TO_MATCH")
      exit 0
    fi
  done
  $("$LOCATED_PREF" "$URL_TO_MATCH")
}

LOCATED_PREF=$(locate_progs "$PREF_BROWSER")
LOCATED_ALT=$(locate_progs "$ALT_BROWSER")

use_alt