3

Im trying to build a conditional statement to search for files of a certain size (in this case 1Gb.

if [ "find /location/sub/int/ -size +1G" ]
then
  > /location/sub/int/large_file_audit.txt
fi

I run this and it creates a file but the file is empty, how can I get the results of the find to populate into the file? what am I doing wrong?

2 Answers 2

6

Your test if [ "find /location/sub/int/ -size +1G" ] doesn't work the way you intend because it tests the non-emptiness of the string "find /location/sub/int/ -size +1G" - which will always be true. In any case, the redirection > /location/sub/int/large_file_audit.txt will not magically pick up the standard output of the preceding command, so will always create an empty file.

Perhaps the closest to your intent in Bash would be to put the results of find into an array, and then test whether it has any elements:

mapfile -t files < <(find /location/sub/int/ -size +1G)

if (( ${#files[@] > 0 )); then 
  printf '%s\n' "${files[@]}" > /location/sub/int/large_file_audit.txt
fi

This won't gracefully handle filenames containing newlines - with newer versions of bash, you could make the find and mapfile null-delimited, but there's not much benefit if you're outputting them as a newline-delimited list anyhow.

4

One liner workaround:

find -size +10G | grep ".*" > file.log || (rm file.log; echo "Can't find anything")

Or:

find -size +10G | grep ".*" > file.log || rm file.log

Note that find returns 1 (False) when files are not processed correctly for any reason, so I suggest using something like:

#!/bin/bash
RESULTS=$(find /path -size +1G)
if [ -n "$RESULTS" ];
 then
   echo "$RESULTS" > /path/file.log
fi

First run the find and put the results in a variable, then if the variable contained anything save that into a log file.

3
  • 2
    While the answer is all correct, you might want to touch on why original if [ "find /location/sub/int/ -size +1G" ] does not work as intended ( and what it actually does instead of what user expects ). Jan 18, 2019 at 22:54
  • 1
    find returns 1 if I ask it to look somewhere that doesn't exist, but if the path exists but -size finds nothing, it does return 0. (and 1 is false).
    – Xen2050
    Jan 19, 2019 at 2:54
  • @Xen2050 To be exact , find returns 1 for any case where directory entries were not processed correctly as stated in EXIT STATUS part of the manual, which includes permission denied error on subdirectories or parent directory (try with chmod -r or touch testdir/subdir/foobar2;chmod -x testdir ). Jan 19, 2019 at 4:40

You must log in to answer this question.

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