Back to Snippets
7 snippets

Disk & File Management

Essential commands for managing disk space, finding large files, cleaning up old data, and auditing file permissions on Linux servers.

Caution:Commands like -delete or rm are irreversible. Always verify the file list first by running the command without the delete flag.

Disk Usage Overview

Shows disk usage and free space for all mounted filesystems in a human-readable format. The -h flag converts bytes to KB/MB/GB automatically.

bash
df -h
# Show only real filesystems (exclude tmpfs/devtmpfs):
df -h --exclude-type=tmpfs --exclude-type=devtmpfs

Top 10 Largest Files or Directories

Identifies and sorts the top 10 largest files or directories consuming disk space. Great for quick cleanup analysis. Replace the path or use '/' for the whole system.

bash
du -ah /path/to/dir | sort -hr | head -n 10

Cleanup Old Log Files

Automatically finds and deletes log files older than 30 days. Run without -delete first to preview the list before deleting.

bash
# Preview first (no deletion)
find /path/to/logs -name "*.log" -type f -mtime +30

# Then delete
find /path/to/logs -name "*.log" -type f -mtime +30 -delete

Find Hidden Dotfiles

Searches for hidden configuration files (like .env, .htaccess) across a directory. Useful for auditing security or finding lost configs.

bash
find /path/to/search -type f -name ".*" -ls

Find World-Writable Files

Lists files that are writable by anyone on the system — a potential security risk. Always audit these on public-facing servers.

bash
find /var/www -type f -perm -o+w -ls 2>/dev/null

Inode Usage Check

Check inode usage per filesystem. A disk can run out of inodes even when there is free disk space, causing 'no space left' errors with small files.

bash
df -i
# Check which directory has the most files (inode hog):
for i in /var/*; do echo -n "$i: "; find "$i" | wc -l; done | sort -t: -k2 -rn | head

Truncate a Log File Safely

Empties a log file without deleting it (which could break running processes still writing to it). Safer than rm + touch.

bash
# Safe truncation — keeps the file descriptor open
truncate -s 0 /path/to/app.log

# Or using redirection:
> /path/to/app.log