bash 如何将grep输出重定向到变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25710640/
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 11:18:49  来源:igfitidea点击:

How to redirect grep output to a variable?

bashvariablesgrepoutputpipe

提问by Denis

I have some pipe. For example, I have this pipe:

我有一些管子。例如,我有这个管道:

user@user:~$ cal | head -1 | grep -oP "[A-Za-z]+"

For this pipe I get this result:

对于这个管道,我得到了这个结果:

September

I want to store this result to a variable. I write the following commands:

我想将此结果存储到变量中。我写了以下命令:

user@user:~$ cal | head -1 | month=$(grep -oP "[A-Za-z]+") | echo $month

And I get the blank string. What is the problem?

我得到了空白字符串。问题是什么?

回答by Cyrus

 month=$(cal | head -1 | grep -oP "[A-Za-z]+")

or

或者

 month=$(date +%B)