来自带有管道、引号等的命令的 Bash 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15256149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:45:46  来源:igfitidea点击:

Bash variable from command with pipes, quotes, etc

bashvariablespipe

提问by TryTryAgain

I have a command I'm using to get the hostname.localdomain:

我有一个用于获取 hostname.localdomain 的命令:

dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; =substr(,1,length()-1); print  ; exit }'

This nicely returns a result like:

这很好地返回了如下结果:

michael.lawler.localdomain.com

michael.lawler.localdomain.com

I'd like to further use that result as a variable in a Bash script.

我想进一步将该结果用作 Bash 脚本中的变量。

It seems I'm having trouble getting past the first pipe.

看来我在通过第一条管道时遇到了麻烦。

If I VAR="dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }'"

如果我 VAR="dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }'"

...I get back the entire zone transfer. I've also tried many minor changes, adding $before the digcommand, without quotes, but nothing seems to work. How can I fix this?

...我拿回了整个区域转移。我还尝试了许多小的更改,$dig命令之前添加,没有引号,但似乎没有任何效果。我怎样才能解决这个问题?

回答by William Pursell

VAR=$( dig axfr @dc1.localdomain.com localdomain.com |
     grep -i Lawler |
     awk '{ getline ; =substr(,1,length()-1); print  ; exit }' )

回答by bchurchill

Use backtics instead of quotes:

使用反引号代替引号:

VAR=`dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; =substr(,1,length()-1); print  ; exit }'`

Backtics actually mean "run whatever is in here and return standard out as the expression's value", but quotes don't do that.

Backtics 实际上意味着“运行这里的任何内容并返回标准输出作为表达式的值”,但引号不会这样做。