88

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?

oguz ismail
  • 1
  • 16
  • 47
  • 69
Rahul KP
  • 1,033
  • 2
  • 9
  • 10
  • you are probably better off using `ls -1` (number one) instead of `ls -l` and `grep -cE` depending on your system? – beroe Nov 13 '13 at 18:30

1 Answers1

130

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 2
    Is it possible to save the variable, but still keep the terminal output at the same time? – Leo May 06 '16 at 06:40
  • @Leo I don't think it is possible. You can probably use an intermediary file for this: `command | tee tmp_file` and then `var=$(< tmp_file)`. This performs the command; with `tee` you see it in terminal output and it is stored in the file `tmp_file` as well; then, you read the file into `$var`. – fedorqui May 06 '16 at 08:06
  • 1
    I just made it with an additional pipe `tee`. `result=$(ls -l | tee /dev/tty | grep -c "rahul.*patle")` – Leo May 06 '16 at 08:32
  • @Leo oh, that's a good one! I had just asked a question about it: [How to store the output of a command in a variable at the same time as printing the output?](http://stackoverflow.com/q/37067895/1983854). Feel free to incorporate your comment there, to make it a general reference. – fedorqui May 06 '16 at 08:42