I am configuring an LDAP server from a bash script and I need to convert the fully qualified domain name (FQDN) to ldap DNs.
For example:
- com -> dc=com
- world.com -> dc=world,dc=com
- hello.world.com -> dc=hello,dc=world,dc=com
- hello.beautiful.world.com -> dc=hello,dc=beautiful,dc=world,dc=com
My bash function works, but it is a little bit verbose. Is there any built-in one-line bash command that I can use? Or how to make my function less verbose?
My code:
#!/bin/bash
function fqdn_to_ldap_dn() {
local fqdn parts dn
fqdn="$1"
IFS=. parts=(${fqdn##*-})
dn=""
for i in "${parts[@]}" ; do
dn+="dc=$i,"
done
dn=${dn%?};
echo $dn
}
echo $(fqdn_to_ldap_dn "aa.hello.com")
Something like this will work:
Wrapping that in the following script:
We get:
Breaking down that command a bit, we have:
${1//./ /}replace all instances of.in$1with(a space). See the "Parameter Expansion" section of the Bash man page for details.The
sedexpressions/[^ ]*/dc=&/gsearches for all groups of non-space characters and addsdc=in front of them (the&in the replacement means "whatever we matched in the first part of the expression").The
sedexpressions/ /,/greplaces all spaces with,