-1

This is what I have but I am pretty sure this only removes the files in the directory and its direct subdirectories. How would I target all subdirectories?

    #!/bin/bash
    currDir="$PWD" #the current working directory is set as the default

    if [ $# -eq 1 ] #if the number of command line args is 1
    then
         currDir=$1 #use the specified directory
    fi

    for file in $currDir/*; #iterate through all the files in the directory
    do
          if [ -s $file ] #if file exists and is not empty
          then
               continue #do not remove
          else
               rm -rf $file #if it exists and is empty, remove the file
          fi
          for file2 in $currDir/**/*; #remove empty files from subdirectory 
          do
              if [ -s $file2 ]
              then
                   continue
              else
                   rm -rf $file2
              fi
          done
     done
  • 2
    Why the requirement to not use the best tool for the job? Also notice how large sections of https://mywiki.wooledge.org/BashFAQ/ are devoted to variations of this. – tripleee Oct 10 '20 at 09:31

2 Answers2

0

You can issue:

find /path/to/your/directory -size 0 -print -delete

This will delete all the files in a directory (and below) that are size zero.

1218985
  • 7,531
  • 2
  • 25
  • 31
0

Would you pleaae try the following:

#!/bin/bash

traverse() {
    local file
    for file in "$1"/*; do
        if [[ -d $file ]]; then
            traverse "$file"
        elif [[ -f $file && ! -s $file ]]; then
            echo "size zero: $file"
            # if the result is desirable, replace the line above with:
            # rm -f -- "$file"
        fi
    done
}

traverse .      # or set to your target directory
tshiono
  • 21,248
  • 2
  • 14
  • 22