How to store command results in a shell variable?

BashShell

Bash Problem Overview


I want to find out the number of directories and files in home directory and store that in a shell variable. I am using the following set of commands.

command="ls -l | grep -c \"rahul.*patle\""
eval $command

I want to store the result in a variable. How can I do this?

Bash Solutions


Solution 1 - Bash

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRahul KPView Question on Stackoverflow
Solution 1 - BashfedorquiView Answer on Stackoverflow