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?

- 8,483
- 2
- 23
- 54

- 43
- 8
2 Answers
Simply use the -p
switch of rmdir
:
Remove all directories in a pathname. For each dir operand:
- The directory entry it names shall be removed.
- 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
)

- 246,190
- 53
- 318
- 364
-
I don't want to delete /mnt :) – Сиволапый Jun 23 '23 at 10:40
-
@Сиволапый is `/mnt` empty? I assume it isn't → it will not be deleted. Also, `/` is usually owned by root, so you cannot delete directories from there. – knittl Jun 23 '23 at 10:41
-
/mnt folder maybe empty. – Сиволапый Jun 23 '23 at 10:44
-
@Сиволапый is it always `/mnt` or is that part dynamic too? How do you know which directories to delete and which to keep? – knittl Jun 23 '23 at 10:48
-
Yes it is always /mnt, dynamic only what comes after /mnt – Сиволапый Jun 23 '23 at 10:52
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.

- 28,885
- 9
- 68
- 122
-
My path in variable. How can i transform path /mnt/testfolder1/testfolder2 to /mnt/testfolder1 in bash ? – Сиволапый Jun 23 '23 at 10:27
-
-
`rm -rf` is dangerous (it will delete all files and directories), but the `find` solution is wonderful. (But it must be `find /tmp/testfolder1 -depth -type d -empty -delete`) – knittl Jun 23 '23 at 10:55
-
-