1

I need the number of total files in a directory and want to use this number in a shell script. I tried this in terminal and it works fine:

find . -type f | wc -l

It just prints the number of files, but I want to assign the returned number to a variable in my shell script, I tried this, but it doesn't work:

numberOfFiles = find . -type f | wc -l;
echo $numberOfFiles;
fedorqui
  • 275,237
  • 103
  • 548
  • 598
AshKan
  • 779
  • 2
  • 8
  • 22

2 Answers2

1

To store the output of a command, you need to use the var=$(command) syntax:

numberOfFiles=$(find . -type f | wc -l)
echo "$numberOfFiles"

Problems in your current approach:

numberOfFiles = find . -type f | wc -l;
             ^ ^
             | space after the = sign
             space after the name of the variable
      no indication about what are you doing. You need $() to execute the command

You are currently trying to execute the numberOfFiles command with the following parameters: = find . -type f | wc -l;, and it is clearly not what you want to do :)

fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

Try this, when assigning an command output to a variable you need to use `. Or you can also use $(command). Both are right way.

numberOfFiles=`find . -type f | wc -l`;
echo $numberOfFiles;
Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
  • 1
    backticks are quite outdated and `$()` is preferred, since you can nest them. See [Bash Backticks vs Braces](http://stackoverflow.com/q/22709371/1983854) for example. – fedorqui Jan 14 '15 at 12:58
  • 1
    yeah I know, still sometimes I can't refrain from using back-ticks, cause used it lots of time since studying, it's became a habit. Thanks for the link @fedorqui it's quite informative. – Arnab Nandy Jan 14 '15 at 13:05