Automatically solve rm cannot remove path : device or resource busy error
Asked Answered
G

3

9

I am trying to remove a directory /path/to/dir using the rm -rf command. Unfortunately I get the error

rm: cannot remove '/path/to/dir/.nfsdda293a660f276ca0000000a': Device or resource busy

After a little bit of research, I realized that I need to find which process is using this file before I can delete it:

lsof /path/to/dir/.nfsdda293a660f276ca0000000a

which will return something with the PID associated with the process:

COMMAND   PID
python    28594

I then kill the PID and try again to delete, but I still get the initial error.

How to force the script to delete /path/to/dir automatically within a script, without manual intervention?

Greensward answered 22/4, 2022 at 1:32 Comment(2)
Do in the script exactly what you do manually. Capture the output of lsof to get the PID to kill and kill it the same method as you would manually.Atli
@Nic3500, why use lsof then instead of fuser -k to do both steps (find the process and kill it) at once?Deranged
T
8

This worked for me:

lsof +D /path

That will recurse through the filesystem under /path, so beware doing it on large directory trees.

Once you know which processes have files open, you can exit those apps, or kill them with the kill(1) command.

Credit: https://unix.stackexchange.com/questions/11238/how-to-get-over-device-or-resource-busy

Tameshatamez answered 24/4, 2022 at 23:50 Comment(0)
C
5

With so many complicated answers on here which is confusing everybody, please just do the following.

umount directoryname

then try again e.g.

rm -rf directoryname
Cascabel answered 17/8, 2023 at 12:34 Comment(1)
umount doesn't work while there are open handles, unless using -f (to "force" the unmount and make future syscalls made by the running programs fail) or -l (a "lazy" unmount, that only does half the job immediately and does the other half when the handles are closed... meaning that the filesystem isn't really released immediately).Deranged
C
1

In case the @Hayden answer didn't help you (returns nothing or such), this command can be handy:

umount /path

credit

Cinerarium answered 28/3, 2023 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.