简体   繁体   English

Bash在单行命令中的另一个变量中扩展变量

[英]Bash expand variable within another variable in a single line command

I'm trying to extract FQDN for a CentOS 7.3 host. 我正在尝试为CentOS 7.3主机提取FQDN。 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 . 第二行的原因是dig输出返回一个点. at the end for eg abc@def.com. 最后,例如abc@def.com. . And hence the 2nd line to strip the last character ie . 因此第二行剥去最后一个字符即.

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)%.} . 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 . 我提到了这个 ,也是这个

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. 但它不是更干净,只是更慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM