Search A-Z index Help
University of Cambridge Home Physics Dept Home Mike Roses' Home Page TCM Group Home

Recursively remove/delete a directory structure that is too big for the rm -rf command (path too long)

rm -rf directory
fails with "path too long"

You can try using Perl and rmtree, but even that might not work, so what do you do?

Use the mvcommand and stay in the current directory to move all sub-directories up one, and iterate. (thanks for Ben Harris of UCS UNIX support for the idea of using mv)

#!/bin/sh

echo "DO NOT RUN as root"

dirs_left=1

# loop until no directories left
while [ ${dirs_left} -eq 1 ]
do

 dirs_left=0
 for name in *
 do
  # if $name is a directory then mv $name/* . and dirs_left=1 and rmdir $name
  if [ -d $name ]
  then
   echo "mv $name \n"
   mv $name/* .
   dirs_left=1
   rmdir ${name}
  fi
 done

 if [ ${dirs_left} -eq 0 ]
 then
  exit 0
 fi

done
This is a little lazy as it will fail with duplicate directories/files being moved into the same directory, but it worked for one case I had to deal with.

It is fairly safe as the script does not use cd or rm although if run as root in / the results would be interesting.

To deal with duplicate files just cd into each sub-directory from the start directory, mv ${thing} ${thing}$$, etc.