Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable contains a domain name in a set of TLDs

Tags:

bash

shell

I have a variable name which contains name of DNS record. I want to check for certain conditions, for example if it ends with .com or .es.

Right now I am using

name="test.com"

namecheck=`echo $name | grep -w  "^[A-Za-z]*..com"`

but it only checks the com and ignores the . also is it possible to check it against series of value stored in array like

domain=[ ".es" ".com" ".de"]
like image 599
rmaan Avatar asked Dec 19 '22 20:12

rmaan


2 Answers

Pure bash implementation:

name=test.com
domains=(es com de)
for dom in ${domains[@]}; do
    [[ $name == *.$dom ]] && echo $name && break
done
like image 93
janos Avatar answered May 26 '23 11:05

janos


You can use this egrep:

egrep -q "\.(com|es|de)$"

This will return 0 (true) if given input is ending with .com OR .es OR .de

EDIT: Using it with an array of allowed domains:

domain=( "es" "com" "de" )
str=$(printf "|%s" ${domain[@]})
str="${str:1}"

echo "abc.test.com"|egrep "\.(${str})$"
abc.test.com

echo "abc.test.org"|egrep "\.(${str})$"
like image 35
anubhava Avatar answered May 26 '23 09:05

anubhava