clear multiple directories with rm

5,458

How about accomplishing it all in a single command?

You can capture the file existence check, globbing and removal with one find call. In the case of GNU's version of find we'd have this:

for f in "${array[@]}"; do
     find "$f" -type f -delete
done

If you don't have GNU find use this invocation:

find "$f" -type f -exec rm -f {} +

(If instead of clearing files from the entire directory hierarchy you only want to clear files that are immediate children then add -maxdepth 1 before -type f.)

But wait, there's more....

As John1024 wisely notes you can forgo the loop altogether by passing the array as the first parameter to find:

     find "${array[@]}" -type f -delete

That's because: 1) find will accept multiple directories to be searched and processed in one execution 2) the shell will split the array such that each element (directory) becomes an individual positional parameter to find.

Share:
5,458
Michael Riordan
Author by

Michael Riordan

Updated on September 18, 2022

Comments

  • Michael Riordan
    Michael Riordan almost 2 years

    I am trying to clear multiple directories stored in an array. Here's a simplified example (I have more directories).

    #!/bin/bash    
    
    $IMAGES_DIR="/Users/michael/scripts/imagefiles"
    $BACKUP_DIR="/Users/michael/scripts/imagebackups"
    
    ...
    
    array=( $IMAGES_DIR $BACKUP_DIR )
    for i in ${array[@]}
    do
        if [ "$(ls -A $i)" ]; then     # check that directory has files in it
            rm "$i/"*                  # remove them 
        fi
    done
    

    I get errors for each directory, e.g.:

    rm: /Users/michael/scripts/imagefiles/*: No such file or directory

  • John1024
    John1024 over 6 years
    Simpler: find "${array[@]}" -type f -delete
  • B Layer
    B Layer over 6 years
    Good one @John1024 ... I shoulda thought of that.
  • smw
    smw over 6 years
  • Praveen Kumar BS
    Praveen Kumar BS over 6 years
    @steeldriver As cross verified from above command I am getting the same result let me know if there is any difference in output
  • Kusalananda
    Kusalananda almost 5 years
    Note that using the expansion of array would split it on whitespaces as well as expand any other shell globbing characters in the pathname (apart from the * that you add to the end).
  • Kusalananda
    Kusalananda almost 5 years
    This would fail on any file whose name contains whitespace or backslashes. Also, since you're removing files (not directories), why are you using -r with rm?