0

I have a path like /mnt/testfolder1/testfolder2 in a variable, I want to check that each folder is empty and then delete it (testfolder2 then testfolder1). How can I do this in bash?

Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54

2 Answers2

2

Simply use the -p switch of rmdir:

Remove all directories in a pathname. For each dir operand:

  1. The directory entry it names shall be removed.
  2. If the dir operand includes more than one pathname component, effects equivalent to the following command shall occur: rmdir -p $(dirname dir)
path='/mnt/testfolder1/testfolder2'
rmdir -p "$path"

You can also ignore the /mnt prefix with standard parameter expansion:

path='/mnt/testfolder1/testfolder2'
cd "${path%{${path#/*/}}" # cd /mnt/
rmdir -p "${path#/mnt/}"  # rm -p testfolder1/testfolder2
cd -                      # go back to previous directory

Alternatively, implement the logic yourself: Try to delete the directory (it will fail if not empty), then strip the last component with each loop iteration:

path='/mnt/testfolder1/testfolder2'
while rmdir "$path" 2>/dev/null; do
  path="${path%/*}"
done

To stop at /mnt:

path='/mnt/testfolder1/testfolder2'
while [ "$path" != '/mnt' ] && rmdir "$path" 2>/dev/null; do
  path="${path%/*}"
done

I want to highlight umläute's find based solution as well, albeit with a slight modification:

path='/mnt/testfolder1/testfolder2'
find "${path%${path#/*/*/}}" -depth -type d -empty -delete

This will only delete empty directories, starting with the leaf directories. The parameter expansion only keeps the first 2 components of the path (mnt and testfolder1)

knittl
  • 246,190
  • 53
  • 318
  • 364
1

just delete recursively:

rm -rf /mnt/testfolder1

as an explanation:

$ man rm
[...]
       -f, --force
              ignore nonexistent files and arguments, never prompt
[...]
       -r, -R, --recursive
              remove directories and their contents recursively

if you only want to delete empty folder, you can use:

find /tmp/testfolder1 -depth -type d -delete

using man find to find out what this actually does it left as an exercise to the user.

umläute
  • 28,885
  • 9
  • 68
  • 122