February 18th 2018

bash

Bash: Test if a string is a web link


I sometimes need this in my scripts: if a string starts with either http:// or https://, it must be a web link. How can I test for that in a single query?

Like this:

$ restore="$(shopt -p extglob)"
$ shopt -s extglob
$ x="http://wiki.archlinux.org/index.php"
$ [[ "$x" == http?(s)://* ]] && echo yes || echo no
yes
$ x="https://wiki.archlinux.org/index.php"
$ [[ "$x" == http?(s)://* ]] && echo yes || echo no
yes
$ x="httpx://wiki.archlinux.org/index.php"
$ [[ "$x" == http?(s)://* ]] && echo yes || echo no
no
$ $restore

This can even be expanded to contain the often gratuitous www.:

[[ "$x" == http?(s)://?(www.)* ]]

Real life example: a script that plays a given link with mpd/mpc if it's a soundcloud URL, and otherwise uses mpv:

#!/bin/bash
shopt -s extglob
if [[ "$1" == http?(s)://?(www.)soundcloud.com/* ]]; then
    mpc clear
    mpc load "soundcloud://url/$1"
    mpc play
    mpc save "$(mpc -f '%name%'|head -1)"
else
    exec mpv "$1"
fi