4

I have a script that downloads 17 files from a FTP server every time, but sometimes some files weigh "0" for some reasons.

So I'm searching for a bash script that checks if there are any files whose size is zero.

How could I do this?

EDIT: I would like to use an if-else statement: if there were any 0 byte files, I will have to run a bash script again.

1 Answer 1

7

If you just want to list the 0-byte files, you can use find:

Example using find:

$ find . -type f -size 0b
./4.txt
./5.txt
./6.txt

The advantage of using find is that you can easily pipe it to xargs to do what you want with the files (such as deleting them), which is much easier than using a for loop.

If you are looking to do something with these files after finding them, for instance, deleting all of the 0-byte files (while accounting for weird file names), I would do something such as this:

$ find -type f -size 0b -print0 | xargs -0I file rm -v file
removed ‘./4.txt’
removed ‘./5.txt’
removed ‘./6.txt’

Additionally, another option to simply list all the files in the directory along with file size in human-readable format, use du -h.

Example using du:

$ du -h *
1.0K    1.txt
1.0K    2.txt
1.0K    3.txt
0       4.txt
0       5.txt
0       6.txt

EDIT: As long as you know how to find the empty files, you can perform additional operations in a number of ways. The following example may not be the best way of going about doing it, but if you are absolutely looking for an if/else statement, then you could do something like this:

#!/bin/bash

for i in *; do
  if [[ $(du -h "$i" | awk '{print $1}') = 0 ]]; then
    echo "$i is empty."
  else
    echo "$i is not empty."
  fi
done

Returns:

1.txt is not empty.
2.txt is not empty.
3.txt is not empty.
4.txt is empty.
5.txt is empty.
6.txt is empty.
2
  • @Giacomo - I have updated my answer to reflect your request for an if/else operation. Commented Oct 17, 2015 at 23:04
  • wc -c works as well, in place of du -h. :)
    – h.j.k.
    Commented Oct 18, 2015 at 3:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .