When attempting to delete a directory in Linux using rm -rf
, you might encounter the frustrating "Device or resource busy" error. This commonly occurs with system directories like /var/www/html
that are actively being used by services or mounted devices.
Here are typical situations where you'll see this error:
- The directory is currently mounted (NFS, bind mounts, etc.)
- A process has files open within the directory
- The directory is being used as a working directory by some process
- It's part of an active chroot environment
First, identify what's using the directory:
# Find mounted filesystems
mount | grep /var/www/html
# Find processes using the directory
lsof +D /var/www/html
# Alternative process check
fuser -vm /var/www/html
Case 1: Directory is Mounted
If it's a mount point, you'll need to unmount first:
umount /var/www/html
rm -rf /var/www/html
Case 2: Processes Using the Directory
For processes locking the directory, either stop them or kill them:
# Graceful stop (Apache example)
sudo systemctl stop apache2
# Force kill all processes using the directory
fuser -km /var/www/html
Case 3: Working Directory Conflict
If a shell or process has it as current directory:
# Find the processes
lsof +D /var/www/html | grep cwd
# Then either:
cd /tmp # if it's your shell
# OR
kill -9 PID # for other processes
For stubborn cases, you can use mount namespaces:
unshare -m
umount -l /var/www/html
exit
rm -rf /var/www/html
- Always check directory usage before deletion
- Consider using
rmdir
for mount points - Implement proper service stopping procedures in scripts
- Use
strace
to debug when other methods fail
When attempting to remove a directory like /var/www/html
with standard rm -rf
commands, Linux systems may return the frustrating "Device or resource busy" error. This typically occurs when:
- The directory is mounted as a filesystem
- Processes have open file handles within the directory
- The directory acts as a working directory for active processes
Before attempting deletion, identify what's locking the directory:
# Find processes using the directory
lsof +D /var/www/html
# Check mount points
mount | grep "/var/www/html"
# Alternative lsof syntax
fuser -vm /var/www/html
Method 1: Unmount First
If the directory is mounted:
umount -l /var/www/html
rm -rf /var/www/html
Method 2: Kill Attached Processes
When processes are using files:
# Kill all processes using the directory
fuser -km /var/www/html
# Then remove
rm -rf /var/www/html
Method 3: The Nuclear Option
For stubborn cases where standard methods fail:
# Reboot into single-user mode
init 1
# Then attempt removal
rm -rf /var/www/html
# Return to normal runlevel
init 5
- Always check directory usage before deletion
- Consider using
lsof
orfuser
in scripts - For web directories, stop Apache/Nginx first
When dealing with NFS or complex mounts:
umount -f -l /mnt/problem_directory
rmdir /mnt/problem_directory