0

This is my first Bash script so forgive me if this question is trivial. I need to count the number of files within a specified directory $HOME/.junk. I thought this would be simple and assumed the following would work:

numfiles= find $HOME/.junk -type f | wc -l
echo "There are $numfiles files in the .junk directory."

Typing find $HOME/.junk -type f | wc -l at the command line works exactly how I expected it to, simply returning the number of files. Why is this not working when it is entered within my script? Am I missing some special notation when it comes to passing options to the utilities?

Thank you very much for your time and help.

Kyle Van Koevering
  • 169
  • 1
  • 3
  • 10
  • Note that your 'find' command was executed with an environment variable 'numfiles' set to the empty string. This can be useful when you want to do it (you can set an env var for the duration of one command without affecting the parent shell), but is a surprise when you don't know that it happens. – Jonathan Leffler Apr 04 '10 at 15:36

3 Answers3

5

You just need to surround it with backticks:

numfiles=`find $HOME/.junk -type f | wc -l`

The term for this is command substitution.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • @Kyle: You're welcome. As you encounter more issues learning Bash scripting (or if you just want to "learn ahead"), I highly recommend reading through the Advanced Bash Scripting Guide as linked in my answer. – Mark Rushakoff Apr 04 '10 at 14:59
  • I will definitely put that guide to good use, thanks again Mark. – Kyle Van Koevering Apr 04 '10 at 15:02
  • 2
    Or, much better, use `$(find $HOME/.junk -type f | wc -l)`. There are fewer problems with nesting the `$(...)` than with back quotes. – Jonathan Leffler Apr 04 '10 at 15:22
4

if you are using bash you can also use $() for command substitution, like so:

numfiles=$(find $HOME/.junk -type f | wc -l)

I find this to be slightly more readable than backquotes, as well as having the ability to nest several commands inside one another.

Yarek T
  • 9,715
  • 2
  • 28
  • 38
1

with bash 4 (if you want recursive)

#!/bin/bash
shopt -s globstar
for file in **
do
 ((i++))
done
echo "total files: $i"

if not

#!/bin/bash
shopt -s dotglob
shopt -s nullglob
for file in *
do 
  ((i++))
done 
echo "total files: $i"
ghostdog74
  • 327,991
  • 56
  • 259
  • 343