Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect grep output to a variable?

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?

like image 323
Denis Avatar asked Sep 07 '14 13:09

Denis


People also ask

How do you redirect output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

Can you use grep with a variable?

Grep works well with standard input. This allows us to use grep to match a pattern from a variable. It's is not the most graceful solution, but it works.

Does grep return a value?

Indeed, grep returns 0 if it matches, and non-zero if it does not. Hence my comment. In the shell 0 means success. Non-zero means failure.


1 Answers

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

or

 month=$(date +%B)
like image 116
Cyrus Avatar answered Sep 20 '22 13:09

Cyrus