Operating System - HP-UX
1828061 Members
2926 Online
109974 Solutions
New Discussion

Shell script: how to check whether a directory is empty?

 
SOLVED
Go to solution
cybermilky
Occasional Contributor

Shell script: how to check whether a directory is empty?

I have a problem on creating a if statement as below. It is suppose to read the source directory and destination directory from the user, then move everything from the source to the destination. If the source is empty, it will stop to move files. How do I check whether a directory is empty?
--------------
#!/bin/sh
echo "Enter source directory: \c"
read dir1
echo "Enter destination directory: \c"
read dir2
pth=$PWD
cd "$dir1"
if [ ??? ] #Problem: How to do the checking here?
then
echo "no files in directory"
else
mv * "$pth"/"$dir2"
echo "Files transfered!"
fi
--------------
How do I do the checking of whether the directory is empty or not?
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Shell script: how to check whether a directory is empty?

How about something as trivial as:

NFILES=$(ls ${dir1} | wc -l)
if [[ ${NFILES} -eq 0 ]]
then
echo "${dir1} is empty".
fi

You might also add some checking to make sure that ${dir1} exists and is a directory.


If it ain't broke, I can fix that.
Robin Wakefield
Honored Contributor

Re: Shell script: how to check whether a directory is empty?

You might want to check for hidden files too, so change the ls to:

ls -a ${dir1}| grep -v -e ^.$ -e ^..$ |wc -l

Rgds, Robin
John Meissner
Esteemed Contributor

Re: Shell script: how to check whether a directory is empty?

empty=$(ls -a | grep -v "." |
grep -v ".." | wc -l)
#!/bin/sh
echo "Enter source directory: \c"
read dir1
echo "Enter destination directory: \c"
read dir2
pth=$PWD
cd $dir1
if [ $empty = "0" ]
then
echo "directory is empty"
else
mv * "$pth"/"$dir2"
echo "Files transfered!"
fi
All paths lead to destiny
John Meissner
Esteemed Contributor

Re: Shell script: how to check whether a directory is empty?

sorry the above post looks funny - i pasted from my term window and it wrapped lines... from the pipe on the first line just continue with what's on the second line....
All paths lead to destiny
John Meissner
Esteemed Contributor

Re: Shell script: how to check whether a directory is empty?

Not to be the point police - but you'll get more responses in the future if you assign points to usefull replies you recieve here.
All paths lead to destiny