Shell script to open a url through terminal

πŸ“… July 8, 2020 β€’ πŸ•£ 1 min read β€’ 517 totalwords

If you are a developer then fixing bugs takes time because you have to shift from terminal to your fav browser & then type your query. (and then in between you open reddit/twitter πŸ˜… for some reason, which wanders your attention).

We can lighten this process a little bit by writing a shell script which will open a URL directly in the browser.

#!/usr/bin/env bash

# Simple script to invoke browser using terminal & search
# Browsers :
# chromium-browser <url>
# firefox --new-tab <url>
# Search Engines :
# Google:<string to search>
# DuckDuckGo:<search_term>
# DuckDuckGo Lite:<search_term>
# GitHub:<string to search>&ref=opensearch

urlencode() {
  local string="${1}"
  local encoded=""
  local pos c o

  for (( pos=0 ; pos<${#string} ; pos++ )); do
     case "$c" in
        [-_.~a-zA-Z0-9] )
                # these characters are url safe (permitted)
                o="${c}" ;;
        * )     
            # Encode special characters
            # Assign output to o, instead of printing to console
            # %02x converts the character into hexadecimal notation.
            printf -v o '%%%02x' "'$c"
  # return "encoded"
  echo "${encoded}" 

read -p "Search Query : " -r search_term

read -p "[F]irefox or [C]hromium ? : "  -n 1 -r BROWSER_CHOICE
  [f/F]* ) firefox --new-tab "$(urlencode "${search_term}")"
  [c/C]* ) chromium-browser "$(urlencode "${search_term}")" 
            exit ;;
  * )     printf "\n%s\n" "[❌]Invalid Input πŸ™„, Try Again";;

You can also view other options to the firefox command by invoking help.

firefox --help

And if you have β€œchromium” installed

chromium-browser --help

Note : If you are on Debian, the command gnome-www-browser will point to the default browser which comes in with your OS, i.e firefox. So both the commands can be easily swapped.

Save this somewhere in your scripts folder and add an alias for it.

alias ddg="/path/to/"
alias helpme="/path/to/"
alias search="/path/to/"

Hope you learned something new today. Take Care πŸ€—