TCSH / CSH / C Shell Check Whether a Directory is Empty or Not

Posted on in Categories last updated July 5, 2011

How do I check whether a directory is empty or not under Linux / UNIX using a TCSH / C shell script?

You can use the following simple code to check if a directory is empty or not using csh:

#!/bin/csh
set dir="$1"
set c=0
# make sure $dir exits 
if ( -d ${dir} ) then
    set c=`ls -a ${dir} | wc | awk '{print $1}'`
   # IS dir is empty
    if ( "${c}" == 2 ) then 
		echo "Empty directory - "${dir}
    else 	#dir has files
		echo "Dir has files - "${dir}
    endif
else 
      echo "Error: Not a directory"
endif

You can use the find command (see your local find man page for exact syntax) as follows:

find "/path/to/dir" -type f -exec echo Found file {} \;

OR

find -type d -empty

See also:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment