Skip to main content

Bash function that validates a URL using a regular expression.

#!/usr/bin/env bash

##
# Validate URL in Bash
#
# References:
# - https://www.codegrepper.com/code-examples/shell/regex+for+url+in+bash
# - https://stackoverflow.com/questions/3183444/check-for-valid-link-url
##

readonly URL_REGEX='^(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]\.[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]$'

is_valid_url() {
    if [[ $1 =~ $URL_REGEX ]]; then
        printf "%s is a valid url\n" "$1"
        return 0
    else
        printf "%s is not a valid url\n" "$1" >&2
        return 1
    fi
}

if [[ -z "${1}" ]]; then
    printf "Usage: %s <url>\n" "$(basename "$0")" >&2
    exit 1
else
    is_valid_url "$1"
fi