Jump to content

Bash: Getting Number/Count of Files in Directory

- - - - -

  • Please log in to reply
No replies to this topic

#1
Tor

Tor

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 486 posts
It isn't hard but I thought I'd post the tip here anyhow. Using the "ls" command "wc" command you can count the number of files in a directory:

# ls <dir> | wc -l

Example:
# ls / | wc -l
  23
# ls /home/tor/*.txt | wc -1
  2

You can assign this to a variable in bash and use it in if statments:

SOMEVAR=`ls <dir> | wc -l`

And now you can test SOMEVAR for 0 (no files) or files.




2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users