0

Okay so I have created such script which basically fetches data from MySQL and store it as a CSV file and push all the files to another server using sftp.

So what I want to create is such a script which basically checks that if the file have any content or not. If the file have no content in it then it basically put in the log that "file Has no content in it" and delete it and also add that in the log, "Deleting that file".

Thanks and regards, Sagar

2 Answers 2

0

Assuming you want to find empty files in the current directory and below, log their paths to a text file called empty.txt and then delete them:

find . ! -path ./empty.txt -type f -empty -print -delete >empty.txt

This assumes that you have a find implementation that understands the non-standard -empty and -delete options. The command avoids deleting the empty.txt file that we're logging to and will otherwise find and delete empty regular files, while outputting their pathnames to the empty.txt file.

You could run the above command without anything after -print to see what would be deleted.

For a standard-compliant variation:

find . ! -path ./empty.txt -type f -exec sh -c '
    for pathname do
        if [ ! -s "$pathname" ]; then
            printf "%s\n" "$pathname"
            rm -f "$pathname"
        fi
    done' sh {} + >empty.txt

This calls a short in-line shell script for batches of found files. The script tests each pathname with the -s test to see whether it's empty or not, and if it is (the -s test is true if it's non-empty, which is why we negate the test), the pathname of the file is printed out and the file is deleted with rm -f.

As before, the output from this is saved to empty.txt.

A shorter but less efficient standard version would be

find . ! -path ./empty.txt -type f \
    ! -exec test -s {} \; -print -exec rm -f {} + >empty.txt

This would be less efficient as it executes the external test command once per file.

1
  • It worked but I wasn't able to add the path to variable pathname so I gave whole path and file name "/created_files/offline_collection$Now.csv instead of pathname . I don't know why this happened. But it worked thanks man
    – user404480
    Commented Apr 18, 2020 at 17:44
0

Command wc -l counts lines of files. This could be a building block:

lineCount=$(<$fileName wc -l)

if [ $lineCount -eq 0 ]; then
  echo "File $fileName has no content"
fi

You must log in to answer this question.