Search code examples
shellawktext-processing

Check file empty or not


I have file which does not have any data in it Need to check below scenario and return file is empty otherwise not empty

if file contains no data but as only spaces return it as FILE is EMPTY 
if file contains no data but as only tabs   return it as FILE is EMPTY
if file contains no data but as only empty new line  return it as FILE is EMPTY  

Does this below code will satisfy all my above cases ? or any best approach all in one go

if [ -s /d/dem.txt ]
then
    echo "FILE IS NOT EMPTY AS SOME DATA"
else
    echo "FILE IS EMPTY NOT DATA AVAILABLE"
fi 

Solution

  • You may use this awk for this:

    awk 'NF {exit 1}' file && echo "empty" || echo "not empty"
    

    Condition NF will be true only if there is non-whitespace character in the file.