Search code examples
bashscriptingfindutilitieswc

Calling linux utilities with options from within a Bash script


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.


Solution

  • You just need to surround it with backticks:

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

    The term for this is command substitution.