存储命令在bash中作为变量输出

时间:2022-05-21 19:32:45

I'm trying to get stored in a variable the output of a command chain with awk, but the result is incomplete,

我试图用awk将命令链的输出存储在变量中,但结果不完整,

this is what im trying to do.

这就是我想要做的事情。

nameserver="nas_server -list all |  awk '{print $6}'"
eval $nameserver
nameserverreal=$nameserver |awk '/encap|nameserver_/{  print }'
eval $nameserverreal

I'm using this command nas_server and with awk print 6, only get some output from my command nas_server.

我正在使用这个命令nas_server和awk print 6,只从我的命令nas_server获取一些输出。

What i need is to filter later the output only with "nameserver_" and storage the output in a variable, so i can print it, and use it later convined with other commands.

我需要的是稍后使用“nameserver_”过滤输出并将输出存储在变量中,这样我就可以打印它,并在以后用其他命令进行后续处理。

1 个解决方案

#1


2  

You appear to be confusing storing the output of commands with storing the text of the commands themselves (which is almost always a bad idea). I'm not sure exactly what you're trying to do (or what the output of nas_server -list all looks like), but I suspect you want something like this:

你似乎混淆了存储命令输出和存储命令本身的文本(这几乎总是一个坏主意)。我不确定你要做什么(或者nas_server -list的输出都是什么样子),但我怀疑你想要这样的东西:

nameserver="$(nas_server -list all |  awk '{print $6}')"   # $() captures the output of a command
echo "$nameserver"  # Double-quote all variable references to avoid parsing weirdness!
nameserverreal="$(echo "$nameserver" |awk '/encap|nameserver_/{  print }')"
echo "$nameserverreal"

Here's a simplified version:

这是一个简化版本:

nameserverreal="$(nas_server -list all |  awk '$6 ~ /encap|nameserver_/ {print $6}'"

Oh, and anytime you're tempted to use eval in a shell script, it's a sign that something has gone horribly wrong.

哦,任何时候你都想在shell脚本中使用eval,这表明事情已经发生了可怕的错误。

#1


2  

You appear to be confusing storing the output of commands with storing the text of the commands themselves (which is almost always a bad idea). I'm not sure exactly what you're trying to do (or what the output of nas_server -list all looks like), but I suspect you want something like this:

你似乎混淆了存储命令输出和存储命令本身的文本(这几乎总是一个坏主意)。我不确定你要做什么(或者nas_server -list的输出都是什么样子),但我怀疑你想要这样的东西:

nameserver="$(nas_server -list all |  awk '{print $6}')"   # $() captures the output of a command
echo "$nameserver"  # Double-quote all variable references to avoid parsing weirdness!
nameserverreal="$(echo "$nameserver" |awk '/encap|nameserver_/{  print }')"
echo "$nameserverreal"

Here's a simplified version:

这是一个简化版本:

nameserverreal="$(nas_server -list all |  awk '$6 ~ /encap|nameserver_/ {print $6}'"

Oh, and anytime you're tempted to use eval in a shell script, it's a sign that something has gone horribly wrong.

哦,任何时候你都想在shell脚本中使用eval,这表明事情已经发生了可怕的错误。