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" ]
  > /location/sub/int/large_file_audit.txt

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?


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

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.

| improve this answer | |

One liner workaround:

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


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:

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

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

| improve this answer | |
  • 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 ). – Sergiy Kolodyazhnyy Jan 18 '19 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 '19 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 ). – Sergiy Kolodyazhnyy Jan 19 '19 at 4:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.