How to check whether directory has files in it or not in shell script?

hi,

I am having script in which i want to check if directory has any file in it or not. If directory contains a single or more files then and only then it should proceed to further operations...

P.S.: Directory might have thousand number of files. so there might be chance of getting error message of argument list too long...
if anyone can help me with this? Code snippet is as follows -

files=directory1/* 
 if [ ${#files[@]} -gt 0 ]     
 then
          tar -czvf $file1.tar.gz directory1/ 
          mv $file1.tar.gz directory2    

Issue is that though directory1 is empty it is going inside if and creating tar file of the empty directory structure. If there are no files under directory1 then i just want to avoid tarring of the same.

Please search. There are various threads stating similar topic.

e.g. the one I found is here

1 Like
if [ `ls | wc -l` -gt 0 ]
1 Like
CNT=`ls $dir/* | wc -l`
  if [ $CNT -eq 0 ]; then
    echo "There are no files in the dir"
  else
    echo "There are files in the dir"
1 Like

GNU Linux:

if find "$dir" -prune -empty | grep -q .
then
  echo "$dir is empty"
fi
1 Like