1

I'm trying to extract FQDN for a CentOS 7.3 host. This is the script I use:

hostname=$(dig +short -x 10.10.10.10)
hostname=${hostname%.}

The reason for the 2nd line is the dig output returns a dot . at the end for e.g. abc@def.com.. And hence the 2nd line to strip the last character i.e .

Is there a way I can do this in one line as a single line command? something like hostname=${$(dig +short -x 10.142.114.44)%.}. Basically, I'm looking to expand variable within another variable. I tried using ${!..} but couldn't make it work and ended up with substitution error. I referred this and also this.

Sandeep Kanabar
  • 1,264
  • 17
  • 33
  • Is the trailing period necessarily a problem? See http://www.dns-sd.org/trailingdotsindomainnames.html. – chepner Mar 14 '18 at 12:55
  • 3
    `${hostname%.}` has various advantages over `${hostname::-1}`. First, I think it more clearly states intent: "Remove the trailing dot from hostname, if there is one." Second, it only removes trailing dots, so it won't fail in mysterious ways on input without a trailing dot. Third, it is Posix standard so it will work with all standard shells. (While zsh and ksh both have substring expansions, neither of them allow negative lengths and both require a starting offset. dash doesn't have substring expansion at all.) – rici Mar 14 '18 at 13:57
  • 1
    Additionally, negative indices work only in Bash 4.2 and newer. – Benjamin W. Mar 14 '18 at 13:58
  • @chepner The reason for this is to get exact hostname that will match the one in SSL certificate. I'm not sure if it'll match with trailing period present. – Sandeep Kanabar Mar 14 '18 at 15:41
  • @rici excellent suggestion. Changed code to use `%.` – Sandeep Kanabar Mar 14 '18 at 15:42

1 Answers1

3

No, parameter expansions can only be applied to parameters, and they can not be nested.

You can do it in a single command by piping your output:

hostname=$(dig +short -x 10.10.10.10 | sed -e 's/\.$//')

but it's not cleaner, just slower.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Ah, the good ol sed. I use it all the time when i want to change lines in files but it slipped my mind that i can apply it here too. – Sandeep Kanabar Mar 14 '18 at 16:01