Sandeep Kanabar
Sandeep Kanabar

Reputation: 1302

Bash expand variable within another variable in a single line command

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.

Upvotes: 1

Views: 125

Answers (1)

that other guy
that other guy

Reputation: 123690

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.

Upvotes: 3

Related Questions