Delete empty files from a directory entered in command prompt

My code to "Delete empty files from a directory entered in command promt"

 
#/bin/sh
echo "Enter directory"
read gh
for file in `ls $gh`
do
# to get the size of file
a=$( ls -l file | awk ' {print $7} ');
echo $a
if [ "$a" = 0 ]
then
echo "removing file "
rm file
 
fi
done

ERROR :

$ ./filsiz1
Enter directory
dir1
ls: cannot access file: No such file or directory

Thanks,
adirajup

That's a useless use of ls.

You don't need ls -l to check if the filesize is zero, either.

You use $file to convert a variable name into the text inside of it, too.

echo "Enter directory"
read gh

if [ ! -d "$gh" ]
then
        echo "$gh doesn't exist or isn't a file"
        exit 1
fi

for file in ${gh}/*
do
        # If we somehow get an invalid filename, ignore it.
        # -e means 'file exists'.
        [ -e "$file" ] || continue
        # -s means "if the file exists and has nonzero size".
        [ -s "$file" ] && continue
        # remove the 'echo' once you've tested this and are sure it works
        echo rm -f "$file"
done
1 Like
find yourdirectory -type f -ls 2>/dev/null | 
while read x x x x x x s x x x f
do
  if [ $s -eq 0 ]; then
    rm -f "$f"
  fi
done
1 Like

It worked .thanks a lot :wink:

    [  -s "$file" ] && continue

what if the file has 0 bytes will "continue" work to remove the file in the next statement

That statement means, "if the file exists and is more than 0 bytes, skip it and go back to the top of the loop".

Empty files don't have more than one byte, and won't skip to the top of the loop.

find "$dir" -mindepth 1 -prune -size 0c -exec rm {} \;

For greater efficiency, replace \; with + .

I don't think the task -- deleting empty files in a user-supplied directory without descending into any subdirectories -- can be reliably accomplished using just POSIX-standard find functionality (mindepth is an extension to POSIX).

In case someone cares to take a stab at it: find.

Regards,
Alister

Thanks for the suggestion..

 
used descending order in code
 
for file in `ls /home/bob/$gh`    do
 
  [ -e "$file" ]  || continue
   [  -s "$file" ] && continue
rm -f "$file"
done