Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to open a URL

Tags:

bash

shell

How do I write a simple shell script (say script.sh), so that I can pass a URL as an argument while executing?

I want a browser to start with the page opened on that URL. I want to write the command in the script to open a browser and open the URL given in argument.

like image 352
darecoder Avatar asked Jul 01 '16 14:07

darecoder


People also ask

How do I open a link in bash?

xdg-open - opens a file or URL in the user's preferred application xdg-open opens a file or URL in the user's preferred application. If a URL is provided the URL will be opened in the user's preferred web browser. If a file is provided the file will be opened in the preferred application for files of that type.

How do I open a URL in Linux?

For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com will open google.com URL in the browser.


2 Answers

You don't need to write a script for that. There're some tools that you can use depending on your OS:

Linux

xdg-open is available in most Linux distributions. It opens a file or URL in the user's preferred browser (configurable with xdg-settings).

xdg-open https://stackoverflow.com 

macOS

open opens files and URLs in the default or specified application.

open https://stackoverflow.com open -a Firefox https://stackoverflow.com 

Windows

You can use the start command at the command prompt to open an URL in the default (or specified) browser.

start https://stackoverflow.com start firefox https://stackoverflow.com 

Cross-platform

The builtin webbrowser Python module works on many platforms.

python3 -m webbrowser https://stackoverflow.com

like image 163
Eugene Yarmash Avatar answered Sep 21 '22 15:09

Eugene Yarmash


Method 1

Suppose your browser is Firefox and your script urlopener is

#!/bin/bash firefox "$1" 

Run it like

./urlopener "https://google.com" 

Sidenote

Replace firefox with your browser's executable file name.


Method 2

As [ @sato-katsura ] mentioned in the comment, in *nixes you can use an application called xdg-open. For example,

xdg-open https://google.com 

The manual for xdg-open says

xdg-open - opens a file or URL in the user's preferred application xdg-open opens a file or URL in the user's preferred application. If a URL is provided the URL will be opened in the user's preferred web browser.
If a file is provided the file will be opened in the preferred application for files of that type. xdg-open supports file, ftp, http and https URLs.

As [ this ] answer points out you could change your preferred browser using say:

xdg-settings set default-web-browser firefox.desktop 

or

xdg-settings set default-web-browser chromium-browser.desktop 
like image 26
sjsam Avatar answered Sep 21 '22 15:09

sjsam