CajunTechie
CajunTechie

Reputation: 605

Find out if a directory has any files in it using Bash?

I'm writing a simple Bash script that needs to find out how many files are in a directory. Basically, if the directory contains no files, the script will exit. If it has any, it will do other things.

How can I find out if there are files in a directory using Bash?

Thanks!

Upvotes: 1

Views: 254

Answers (4)

chepner
chepner

Reputation: 531055

I needed the same thing yesterday, and found this (it's near the bottom of the page):

# From http://www.etalabs.net/sh_tricks.html
is_empty () (
  cd "$1"
  set -- .[!.]* ; test -f "$1" && return 1
  set -- ..?* ; test -f "$1" && return 1
  set -- * ; test -f "$1" && return 1
  return 0 )

It's POSIX-compatible, and uses three patterns to match any file name other than . and .. which are guaranteed to exist in an otherwise empty directory.

The first two lines match all files starting with a single . (of length at least 2) or one or more . (of length at least 3), which covers all hidden files that aren't . or ... The third pattern matches all non-hidden files.

Notice that the body of the function is a (...) expression, not {...}. This forces a subshell, in which it is safe to change the working directory to simplify the patterns.

Upvotes: 0

beroe
beroe

Reputation: 12316

The other answers have shown you ways to get the number of files. Here is how to use the number in your script.

(This is presented in the context of a function, with $1 being the directory name specified when you run it. To use it on the current directory, just omit that, or you can hardwire a directory name in that location.)

checkdir(){
    numfiles=$(ls -A "$1" | wc -l)

    if [ $numfiles -gt 0 ]
    then
       echo YES;
    else
       echo NO;
    fi
}

Note: this will count directories as files. If you would like only files, then replace the ls...wc portion with this line:

ls -AF "$1" | grep -v "/$" | wc -l

Upvotes: 0

Morfic
Morfic

Reputation: 15508

List almost (no . or ..) all files and directories and count the lines: ls -A1 /mydir | wc -l

If you'd like only files I think you can use find instead: find /mydir -maxdepth 1 -type f | wc -l

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185025

shopt -s nullglob
cd /path/to/dir/
arr=( * )
echo "${#arr[@]}"
for i in "${!arr[@]}"; do echo "${arr[i]}"; done

Upvotes: 0

Related Questions