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...

UPDATE

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

#!/bin/bash
if [ -s aFile ]; then
    echo "The File has some data."
else
    echo "The File is empty."
fi

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.

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

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.

#!/bin/bash
_file="$1"
[ $# -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
else
  echo "$_file is empty."
  # do something as file is empty 
fi

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