bash: cannot create temp file for here-document: No space left on device-bash: /root/.bash_history: cannot create temp file for here-document: No space left on device
Your Linux server just hit 100% disk capacity. Applications are crashing, services won't start, and you can't even create new files. This is one of the most stressful server emergencies - but it's fixable.
In this comprehensive guide, you'll learn 15 proven methods to quickly reclaim disk space on Ubuntu, Debian, CentOS, and other Linux distributions. From quick wins (clean APT cache) to deep cleanup (find and remove massive log files), you'll get your server running again.
1.
sudo apt autoremove && sudo apt clean (Ubuntu/Debian)2.
sudo journalctl --vacuum-size=100M (Clean systemd logs)3.
docker system prune -a (If using Docker)These three commands alone can free 2-10GB in seconds!
Step 1: Check Your Disk Usage (Diagnose the Problem)
Before cleaning, see which filesystem is full and how much space each directory uses.
Check Overall Disk Usage:
df -h
Example Output:
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 50G 48G 2.0G 96% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
Look for filesystems at 90%+ usage. In the example above, / (root) is at 96% - that's your problem.
Find Which Directories Are Using the Most Space:
sudo du -sh /* | sort -rh | head -20
This shows the 20 largest directories on your system. Common culprits:
/var- Logs, cache, Docker volumes/home- User files, backups/tmp- Temporary files (should auto-clean)/usr- Old software packages, kernels
ncdu (NCurses Disk Usage) for an interactive disk usage browser:sudo apt install ncdusudo ncdu /Navigate with arrow keys, press
d to delete files.
Method 1: Clean APT Package Cache (Ubuntu/Debian)
Potential Space Saved: 500MB - 5GB
APT stores downloaded .deb packages in /var/cache/apt/archives/. After installation, these are no longer needed.
Clean All Package Cache:
sudo apt clean
Remove Only Outdated Packages:
sudo apt autoclean
Remove Unused Dependencies:
sudo apt autoremove
Complete Cleanup Command:
sudo apt autoremove && sudo apt clean
This is the #1 quickest win on Debian-based systems!
Method 2: Clean YUM/DNF Cache (CentOS/RHEL/Fedora)
Potential Space Saved: 500MB - 3GB
CentOS 7/RHEL 7 (YUM):
sudo yum clean all
sudo yum autoremove
CentOS 8+/Fedora (DNF):
sudo dnf clean all
sudo dnf autoremove
Method 3: Clean Systemd Journal Logs
Potential Space Saved: 1GB - 10GB+
Systemd logs can grow to massive sizes, especially on long-running servers or those with verbose logging.
Check Current Journal Size:
sudo journalctl --disk-usage
Limit Journal to 100MB:
sudo journalctl --vacuum-size=100M
Keep Only Last 7 Days:
sudo journalctl --vacuum-time=7d
Permanently Limit Journal Size:
Edit /etc/systemd/journald.conf:
sudo nano /etc/systemd/journald.conf
Add or modify these lines:
SystemMaxUse=500M
SystemKeepFree=1G
SystemMaxFileSize=100M
Restart journald:
sudo systemctl restart systemd-journald
Method 4: Clean Application Logs in /var/log
Potential Space Saved: 500MB - 20GB+
Application logs can grow massive over time, especially for web servers (nginx/apache), databases (MySQL), and mail servers.
Check Log Directory Size:
sudo du -sh /var/log/*
Find Large Log Files:
sudo find /var/log -type f -size +100M -exec ls -lh {} \;
Delete Compressed Old Logs:
sudo find /var/log -type f -name "*.gz" -delete
sudo find /var/log -type f -name "*.1" -delete
sudo find /var/log -type f -name "*.old" -delete
Truncate (Empty) Large Log Files (Instead of Deleting):
sudo truncate -s 0 /var/log/syslog
sudo truncate -s 0 /var/log/apache2/access.log
sudo truncate -s 0 /var/log/nginx/access.log
sudo truncate -s 0 /var/log/mysql/error.log
Truncating is safer than deleting because it empties the file but keeps it (prevents "file not found" errors).
Set Up Log Rotation (Prevent Future Issues):
Edit /etc/logrotate.conf or create custom configs in /etc/logrotate.d/:
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
}
Method 5: Remove Old Kernels (Ubuntu/Debian)
Potential Space Saved: 500MB - 2GB
Ubuntu keeps old kernel versions when updating. After multiple updates, you might have 5-10 old kernels taking up space.
List Installed Kernels:
dpkg --list | grep linux-image
Check Current Kernel:
uname -r
Auto-Remove Old Kernels:
sudo apt autoremove --purge
This automatically removes all kernels except the current one and the previous one (safety fallback).
Manually Remove Specific Kernel (Advanced):
sudo apt purge linux-image-5.4.0-42-generic
sudo apt purge linux-headers-5.4.0-42-generic
uname -r first.
Method 6: Clean Docker Space (If Using Docker)
Potential Space Saved: 5GB - 50GB+
Docker is notorious for consuming disk space with unused images, stopped containers, and dangling volumes.
Check Docker Disk Usage:
docker system df
Remove Stopped Containers:
docker container prune
Remove Unused Images:
docker image prune -a
Remove Unused Volumes:
docker volume prune
Remove Everything Unused (Nuclear Option):
docker system prune -a --volumes
This removes ALL stopped containers, unused networks, unused images, and unused volumes. Use with caution!
docker system prune -a monthly as part of server maintenance. It's safe and can reclaim 10-20GB instantly.
Method 7: Clean Thumbnail Cache (Desktop/GUI Servers)
Potential Space Saved: 100MB - 2GB
If you use a desktop environment or file manager, thumbnail cache can grow large.
rm -rf ~/.cache/thumbnails/*
rm -rf ~/.thumbnails/*
Method 8: Delete Broken Symlinks
Potential Space Saved: Minimal (but good housekeeping)
Find Broken Symlinks:
find /home -xtype l
Delete Broken Symlinks:
find /home -xtype l -delete
Method 9: Clear /tmp Directory
Potential Space Saved: 100MB - 5GB
Temporary files should auto-delete but sometimes don't. It's safe to manually clear them.
Delete Everything in /tmp (Safe):
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*
These directories are meant for temporary files and can be safely cleared even while the system is running.
Method 10: Find and Delete Large Files
Potential Space Saved: Varies
Find Files Larger Than 1GB:
sudo find / -type f -size +1G -exec ls -lh {} \; 2>/dev/null
Find Files Larger Than 500MB:
sudo find / -type f -size +500M -exec ls -lh {} \; 2>/dev/null
Find Largest 50 Files:
sudo find / -type f -printf '%s %p\n' 2>/dev/null | sort -rn | head -50
Review the list and delete unnecessary files:
sudo rm /path/to/large/file.tar.gz
Disk Management Made Easy - No More Terminal Commands
Manually running disk cleanup commands is tedious and risky. VPS Commander provides a visual disk usage analyzer, one-click log cleanup, and automated maintenance tasks - all through an intuitive web interface. No terminal expertise required.
Try VPS Commander - Starting at $2.99/monthMethod 11: Clean NPM Cache (Node.js Users)
Potential Space Saved: 500MB - 5GB
npm cache clean --force
Check NPM Cache Size:
du -sh ~/.npm
Method 12: Clean Yarn Cache
Potential Space Saved: 500MB - 5GB
yarn cache clean
Check Yarn Cache Size:
du -sh $(yarn cache dir)
Method 13: Clean pip Cache (Python)
Potential Space Saved: 200MB - 2GB
pip cache purge
For pip Older Versions:
rm -rf ~/.cache/pip
Method 14: Remove Unnecessary Packages
Potential Space Saved: 500MB - 3GB
List Installed Packages by Size (Debian/Ubuntu):
dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -rn | head -20
Remove Package:
sudo apt remove package-name
sudo apt purge package-name # Also removes config files
Method 15: Expand Disk or Add Storage (Ultimate Solution)
If you've cleaned everything and still need more space, it's time to expand your disk.
Option 1: Resize Existing Disk (Cloud VPS)
- Go to your hosting provider's control panel
- Increase disk size (usually instant or requires reboot)
- Resize the partition and filesystem
Resize Partition After Expanding (Ubuntu):
sudo growpart /dev/sda 1 # Grow partition 1 on sda
sudo resize2fs /dev/sda1 # Resize ext4 filesystem
Option 2: Add New Disk/Volume
- Attach a new block storage volume
- Format it:
sudo mkfs.ext4 /dev/sdb - Mount it:
sudo mount /dev/sdb /mnt/data - Move large directories (e.g., Docker volumes) to the new disk
Emergency: Disk 100% Full - Can't Even Login
If your disk is so full that you can't even login or run commands, try these emergency tactics:
1. Use Your Hosting Provider's Web Console
Most VPS providers (DigitalOcean, Linode, AWS) offer a web-based console that works even when SSH fails.
2. Boot into Single-User/Recovery Mode
Reboot and enter recovery mode to get a minimal shell with fewer services consuming disk space.
3. Delete Largest Files Blindly (Last Resort):
# Clear journal logs immediately
sudo rm -rf /var/log/journal/*
# Clear all compressed logs
sudo rm -rf /var/log/*.gz
# Clear APT cache
sudo rm -rf /var/cache/apt/archives/*
These commands are destructive but effective when you're locked out.
Prevent Future Disk Space Issues
1. Set Up Log Rotation
Ensure logrotate is enabled and configured properly:
sudo systemctl status logrotate
2. Enable Automatic APT Cleanup
Edit /etc/apt/apt.conf.d/10periodic:
APT::Periodic::AutocleanInterval "7";
3. Set Up Monitoring & Alerts
Use monitoring tools to get alerts when disk usage hits 80%:
- Nagios, Zabbix, Prometheus (self-hosted)
- Datadog, New Relic (SaaS)
- Simple cron job + email alert
Simple Disk Alert Script:
#!/bin/bash
THRESHOLD=80
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt $THRESHOLD ]; then
echo "Disk usage is ${USAGE}%" | mail -s "Disk Alert" admin@example.com
fi
Add to cron: crontab -e
0 */6 * * * /path/to/disk-alert.sh
4. Regular Maintenance Schedule
- Weekly:
apt autoremove && apt clean - Monthly: Review and clean large log files
- Monthly:
docker system prune -a(if using Docker) - Quarterly: Audit installed packages, remove unused ones
Complete Disk Cleanup Checklist
- ✅ Check disk usage:
df -h - ✅ Find large directories:
du -sh /* | sort -rh | head -20 - ✅ Clean package cache:
apt clean && apt autoremove - ✅ Clean systemd logs:
journalctl --vacuum-size=100M - ✅ Delete old compressed logs:
find /var/log -name "*.gz" -delete - ✅ Truncate large log files:
truncate -s 0 /var/log/syslog - ✅ Remove old kernels:
apt autoremove --purge - ✅ Clean Docker:
docker system prune -a - ✅ Clear /tmp:
rm -rf /tmp/* - ✅ Find and delete large files:
find / -size +1G - ✅ Set up log rotation and monitoring
Quick Reference: Disk Cleanup Commands
# CHECK DISK USAGE
df -h
du -sh /* | sort -rh | head -20
sudo ncdu /
# UBUNTU/DEBIAN CLEANUP
sudo apt autoremove && sudo apt clean
sudo apt autoremove --purge # Remove old kernels
# CENTOS/RHEL CLEANUP
sudo yum clean all && sudo yum autoremove
sudo dnf clean all && sudo dnf autoremove
# LOG CLEANUP
sudo journalctl --vacuum-size=100M
sudo find /var/log -name "*.gz" -delete
sudo truncate -s 0 /var/log/syslog
# DOCKER CLEANUP
docker system prune -a --volumes
# FIND LARGE FILES
sudo find / -type f -size +1G -exec ls -lh {} \; 2>/dev/null
# DEVELOPER CACHES
npm cache clean --force
yarn cache clean
pip cache purge
# TEMP FILES
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*
Frequently Asked Questions
Is it safe to delete files in /var/log?
Yes, but truncate instead of delete: truncate -s 0 /var/log/syslog. This empties the file but keeps it, preventing "file not found" errors.
How much disk space should I keep free?
Keep at least 10-20% free. Linux performance degrades when disks are over 90% full, and some applications require free space to function.
What if I delete the wrong files?
Always have backups before aggressive cleanup. Use ls -lh to review files before deleting. Start with safe cleanups (apt cache, old logs) before deleting unknown files.
Can I automate disk cleanup?
Yes! Set up cron jobs for apt autoremove, journalctl --vacuum, and docker system prune. Just be careful with automated deletions of user data.
Conclusion: Reclaim Your Disk Space
Running out of disk space is scary, but with these 15 methods, you can quickly recover gigabytes of space:
Fastest Wins (Do These First):
sudo apt clean && sudo apt autoremove- 1-5GBsudo journalctl --vacuum-size=100M- 1-10GBdocker system prune -a- 5-50GB (Docker users)- Delete old compressed logs - 500MB-5GB
These four commands alone can free 5-20GB on most servers in under 2 minutes.
✅ Set up log rotation (logrotate, journald limits)
✅ Enable disk usage monitoring and alerts
✅ Schedule weekly/monthly cleanup tasks
✅ Regularly audit and remove unused packages
✅ Keep 15-20% disk space free at all times
Don't wait for the "No space left on device" emergency. Make disk cleanup part of your regular server maintenance routine!