Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store command results in a shell variable? [duplicate]

Tags:

bash

shell

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?

like image 894
Rahul KP Avatar asked Nov 13 '13 10:11

Rahul KP


People also ask

How do you save a command output to a variable?

Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables. variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...]


1 Answers

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.

like image 81
fedorqui 'SO stop harming' Avatar answered Sep 23 '22 06:09

fedorqui 'SO stop harming'