如何将命令的输出放在 bash 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14639452/
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
How to put the output of command in bash variable
提问by user2027303
I want to put the output of command in bash variable and then further use that variable in other command
我想将命令的输出放在 bash 变量中,然后在其他命令中进一步使用该变量
Suppose i want something like this
假设我想要这样的东西
ls | $(variable) |awk '/$variable/{print "here"}'
ls | $(variable) |awk '/$variable/{print "here"}'
采纳答案by Hui Zheng
You can try:
你可以试试:
variable=$(ls); awk "/$variable/"'{print "here"}'
Note 1: /$variable/is surrounded by double quotes, otherwise it won't be replaced by output of command.
注1:/$variable/用双引号括起来,否则不会被命令的输出替换。
Note 2: The above command may fail since the output of lsmay contains "/" or newline, which will break the awkcommand. You may change lsto something like ls | tr '\n' ' ' | tr -d '/' | sed 's/ *$//g'(replace all newlines with spaces; delete all slashes; remove the trailing whitespace), depending on your goal.
注意 2:上述命令可能会失败,因为输出ls可能包含“/”或换行符,这会破坏awk命令。根据您的目标,您可以更改ls为类似的内容ls | tr '\n' ' ' | tr -d '/' | sed 's/ *$//g'(用空格替换所有换行符;删除所有斜杠;删除尾随空格)。
Note 3: to avoid variable assignment polluting the current shell's environment, you can wrap the above command by parentheses, i.e. (variable=$(some_command); awk "/$variable/"'{print "here"}')
注3:为避免变量赋值污染当前shell的环境,可以将上述命令用括号括起来,即 (variable=$(some_command); awk "/$variable/"'{print "here"}')
回答by Elalfer
To put command output into variable you can use following format in bash
要将命令输出放入变量中,您可以在 bash 中使用以下格式
variable=`pwd`
echo $variable
回答by Oliver
Or
或者
now=`date`
Back ticks
回勾
Which is easier for me since it works in any shell or perl
这对我来说更容易,因为它适用于任何 shell 或 perl
回答by Carl Norum
I don't know that you can easily do it in a single step like that, but I don't know why you'd pipe it to awkanduse it in the script like that anyway. Here's the two step version, but I'm not really sure what it does:
我不知道您是否可以通过这样的一个步骤轻松完成,但我不知道您为什么要通过管道将它传递给awk并在脚本中像这样使用它。这是两步版本,但我不确定它的作用:
variable=$(ls)
echo ${variable} | awk "/${variable}/{printf \"here\"}"

