How to store command results in a variable in on shellscripting?

Rahul KP picture Rahul KP · Nov 13, 2013 · Viewed 156.6k times · Source

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

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

i want to store this count into some varibale count. How can i do this.

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Nov 13, 2013

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.