Via BASH script, I'm automatically constructing a string like: DC=us,DC=earth,DC=com
for LDAP domain components. But, I won't know how many subdomain components a domain might have.
For example:
dub.sub.domain.tld
needs DC=dub,DC=sub,DC=domain,DC=tld
sub.domain.tld
needs DC=sub,DC=domain,DC=tld
domain.tld
needs DC=domain,DC=tld
But, I don't know which one I'll have, and I need to automatically create this string.
My current solution is:
# The variable we got somehow
indomain="dub.sub.domain.tld"
#IFS='.' #Please no, sed instead...
# Create a loopable list with space as the IFS
domaincomponents=$(echo $indomain | sed 's/\./ /g')
# Process each domain component
finalstring=""
for component in $domaincomponents; do
finalstring=DC=$component,$finalstring
done
# Remove the trailing ,
finalstring=$(echo $finalstring | sed 's/\(.*\),/\1 /')
Result: $finalstring
= DC=tld,DC=domain,DC=sub,DC=dub
...which is in reverse
Not only does this produce the string backwards; it seems over-processed and that a tool like awk
could do a cleaner job.
Is there a better way?
I am assuming that DC=
in LDAP can go as deep as any subdomain name; correct me if I'm wrong.
With sed
:
echo 'dub.sub.domain.tld' | sed 's/^/DC=/; s/\./,DC=/g'
Output:
DC=dub,DC=sub,DC=domain,DC=tld