Check if File Exists AND is not Empty

This is way out of date now

The information in this post is so out-dated that I wonder why I'm keeping it around. I guess I'm a digital hoarder...


HOLY LORD!! I used to write my if-then statements UGLY. Fixed that for my sanity.

Ok, as the title suggests, this is about file state testing.

I was recently writing a script that relied on the contents of a dynamically created file. If the file EXISTS and HAS contents THEN do something with said content.

Sounded simple enough, but my first attempts allowed for false positives

if [ -s aFile ]; then
    echo "The File has some data."
    echo "The File is empty."

The above code will return "The File is empty" even if the file does not exist. To counter that, I added a nested if to check for for this edge case.

if [ -f aFile ] && [ "`ls -l aFile | awk '{print $5}'`" == "0" ]; then
  if [ ! -f aFile ]; then
    echo "File Does Not Exist"
    echo "File Exists and is Empty"
  echo "File Exists and is Not Empty"

I'll admit, this is kind of an ugly solution...

I've since found another way to do this that is a wee bit more elegant.

[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
[ ! -f "$_file" ] && { echo "Error: $0 file not found."; exit 2; }

if [ -s "$_file" ]; then
  echo "$_file has some data."
  # do something as file has data
  echo "$_file is empty."
  # do something as file is empty 

Source of above code

  • Find problem
  • Google it
  • Code a solution
  • Test it
  • Write a blog post about it
  • Find a better way to do it ಠ_ಠ
  • Repeat