views:

33

answers:

3

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.

+4  A: 

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
Thank you very much! It works now.
Kyle Van Koevering
@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
I will definitely put that guide to good use, thanks again Mark.
Kyle Van Koevering
Or, much better, use `$(find $HOME/.junk -type f | wc -l)`. There are fewer problems with nesting the `$(...)` than with back quotes.
Jonathan Leffler
+4  A: 

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
This is also helpful, thank you very much!
Kyle Van Koevering
+1  A: 

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
Interesting information!
Jonathan Leffler