How to get domain name from URL in bash shell script

Here’s a simple bash script to extract the domain name from a URL:

#!/bin/bash

# Input URL
url="$1"

# Extract domain name using parameter expansion and pattern matching
domain=${url#*//} # remove everything up to the first double slashes
domain=${domain%%/*} # remove everything after the first slash

# Output the extracted domain name
echo "Domain name: $domain"

This script uses parameter expansion and pattern matching in bash to extract the domain name. The first line ${url#*//} removes everything up to the first double slashes (//) in the URL. The second line ${domain%%/*} removes everything after the first slash (/) in the remaining string, which is the extracted domain name.

You can run this script by passing a URL as an argument:

$ ./script.sh http://www.example.com/path/to/page

This will output:

Domain name: www.example.com

Leave a Comment