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?
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 ...]
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.
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.
month=$(cal | head -1 | grep -oP "[A-Za-z]+")
or
month=$(date +%B)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With