[BASH] Quickly deleting empty files in a directory.


I thought up of the following BASH one-liner half an hour ago to remove lots of empty or zero byte files from a directory. I have prettified the presentation of the one-liner below, but you may safely pull all the lines together into a single line and use it on BASH. Do note that the actual command to remove the files has been stashed inside an echo command for safety.

for file in *;
  do
    file_size=$(du $file | awk '{print $1}');
    if [ $file_size == 0 ]; then
        echo "Deleting empty file $file with file size $file_size!";
        echo "rm -f $file";
    fi;
  done

11 thoughts on “[BASH] Quickly deleting empty files in a directory.

  1. I’ve another way still – but first…

    Using find -print0 and xargs -0 implies GNU find and GNU xargs – which are not always present. Also, xargs requires a binary and echo is a builtin – but since it is usually ALSO a binary, it may be okay.

    Here’s my alternative:

    for i in * ; do [ ! -s “${i}” ] && echo rm -f “${i}” ; done

    This should be fastest: there is only one binary in this sequence; the rest are builtins.

    Depending on how many there are, this might even be faster:

    echo rm -f $(for i in *; do [ ! -s “$(i)” ] && echo $i)

    Again, no binaries but rm – but in this case only one rm call, not one for each file.

    (note the echo failsafe here as well)

  2. @azimyasin: ingenious!

    However, there are two flaws: 1) the find command will descend indefinitely; 2) that command will delete empty directories as well.

    How about:

    rm -f $(find . -maxdepth=1 -type f -empty)

    However, it still requires loading find and rm instead of just rm; my examples used shell built-ins for their speed.

    Those examples are also compliant with ksh, not just bash I might add.

  3. I wrote this in a script years ago:

    rm -f $(ls -l |awk ‘$5 == “0” {print $NF}’)

    .. these days I’d just use ‘find . -empty -exec rm -f {} \;

  4. The command above of the form “rm -f $(…)” and “rm -f `…`” are unsafe when filenames contain spaces. Consider an empty file named “/home/mine/humpty/dumpty .profile”. The commands will effectively remove my “.profile”, and won’t even try to remove the empty file.

    (The commands above using “for i in *;…rm -f “$i””, “find…-exec” and “find…-print0” are safe in this regard.)

  5. You could simply add the parameter ‘-delete’ to the find command instead of redirecting the output to another command like this:
    find -name “*.txt” -empty -delete

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s