Powerful Code Snippets

Production-ready Ubuntu, Bash, and PowerShell 7 commands for sysadmins and developers

Complete macOS Keyboard Shortcuts Guide for Developers

January 26, 2026 Updated February 24, 2026
macos keyboard shortcuts terminal vscode developer apple m1 productivity

Switching from Windows to a MacBook can feel disorienting at first. The keyboard layout looks similar, but the shortcuts are completely different. This comprehensive reference guide is designed specifically for developers and power users making the transition to macOS, particularly on Apple Silicon Macs like the M1 Pro.

The Essential Mental Shift: Key Mapping

Before diving into specific shortcuts, understanding how keys translate between Windows and macOS is crucial:

Windows Key macOS Equivalent Symbol
Ctrl⌘ Command⌘
Alt⌥ Option⌥
Windows Key⌘ Command⌘
BackspaceDelete⌫
Delete (Forward)Fn + Delete⌦

Critical Insight: On macOS, most shortcuts that used Ctrl on Windows now use ⌘ Command. However, in Terminal, Ctrl is still Ctrl for Unix commands like Ctrl+C to kill a process.

Essential System Shortcuts

Window & App Management

ShortcutAction
⌘ + QQuit application (not just close window!)
⌘ + WClose current window/tab
⌘ + HHide current application
⌘ + MMinimize window to Dock
⌘ + TabSwitch between applications
⌘ + `Switch between windows of same app
⌘ + ,Open Preferences (works in almost every app)
⌃ + ⌘ + QLock screen
⌘ + ⌥ + EscForce Quit dialog (like Ctrl+Alt+Del)
⌃ + ⌘ + FToggle fullscreen

Screenshot Shortcuts (Built-in, No Software Needed)

ShortcutAction
⌘ + ⇧ + 3Screenshot entire screen
⌘ + ⇧ + 4Screenshot selection (crosshair)
⌘ + ⇧ + 4, then SpaceScreenshot specific window
⌘ + ⇧ + 5Screenshot/recording toolbar
Add ⌃ to anyCopy to clipboard instead of file

Text Editing Navigation

This is where macOS truly shines compared to Windows:

ShortcutAction
⌘ + ←Beginning of line
⌘ + →End of line
⌘ + ↑Beginning of document
⌘ + ↓End of document
⌥ + ←Previous word
⌥ + →Next word
⌃ + ABeginning of line (Unix style)
⌃ + EEnd of line (Unix style)
⌥ + ⌫Delete word before cursor
⌘ + ⌫Delete to beginning of line

Pro Tip: Add ⇧ Shift to any navigation shortcut to select text. For example, ⇧ + ⌘ + → selects from cursor to end of line.

Terminal Shortcuts (Bash/Zsh)

For developers, these terminal shortcuts are essential. They work the same whether you're on your local Mac or SSH'd into a Linux server.

Navigation & Editing

ShortcutAction
⌃ + AMove to beginning of line
⌃ + EMove to end of line
⌥ + FMove forward one word
⌥ + BMove backward one word
⌃ + UDelete from cursor to beginning of line
⌃ + KDelete from cursor to end of line
⌃ + WDelete word before cursor
⌃ + YPaste previously deleted text (yank)
⌃ + _Undo last edit

History & Process Control

ShortcutAction
⌃ + RReverse search history (incredibly useful!)
⌃ + P or ↑Previous command
⌃ + N or ↓Next command
⌃ + CKill current process (SIGINT)
⌃ + ZSuspend process (use fg to resume)
⌃ + DEOF / Exit shell (if line is empty)
⌃ + LClear screen (same as clear)
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponderFlush DNS Cache

Terminal App Specific

ShortcutAction
⌘ + TNew tab
⌘ + DSplit pane vertically
⌘ + ⇧ + DSplit pane horizontally
⌘ + KClear scrollback
⌘ + + / -Increase/decrease font size

Finder Shortcuts

Finder is macOS's file manager. These shortcuts will help you navigate efficiently:

ShortcutAction
⌘ + ⇧ + GGo to folder (type path directly)
⌘ + ⇧ + HGo to Home folder
⌘ + ⇧ + DGo to Desktop
⌘ + ⇧ + OGo to Documents
⌘ + ⇧ + LGo to Downloads
⌘ + ⇧ + .Show/hide hidden files
EnterRename file (not open!)
SpaceQuick Look preview
⌘ + ⌫Move to Trash
⌘ + ⌥ + VMove files (instead of paste, after ⌘+C)
⌘ + ⌥ + CCopy file path

VS Code Shortcuts (macOS)

For web developers, these VS Code shortcuts are essential:

Essential Editing

ShortcutAction
⌘ + DSelect word / Add selection to next match
⌘ + ⇧ + LSelect all occurrences of selection
⌥ + ↑ / ↓Move line up/down
⌥ + ⇧ + ↑ / ↓Copy line up/down
⌘ + ⇧ + KDelete line
⌘ + /Toggle line comment
⌘ + ⇧ + AToggle block comment
⌥ + ZToggle word wrap

Navigation & Panels

ShortcutAction
⌘ + PQuick open file
⌘ + ⇧ + PCommand palette
⌘ + ⇧ + OGo to symbol in file
⌘ + GGo to line
⌃ + `Toggle terminal
⌘ + BToggle sidebar
F12Go to definition
⌥ + F12Peek definition
F2Rename symbol

Browser Developer Tools (Chrome/Safari)

ShortcutAction
⌘ + ⌥ + IOpen DevTools
⌘ + ⌥ + JOpen Console
⌘ + ⌥ + UView source
⌘ + ⇧ + CInspect element
⌘ + ⇧ + RHard reload (clear cache)
⌘ + ⇧ + TReopen closed tab

Common Gotchas for Windows Users

⚠️ Things That Will Trip You Up

  1. ⌘ + Q quits apps entirely — Not just minimizes. Use ⌘ + H to hide instead.
  2. Delete key is Backspace — For forward delete, use Fn + Delete.
  3. Home/End work differently — Use ⌘ + ← / → for line start/end.
  4. No cut in Finder — Use ⌘ + C then ⌘ + ⌥ + V to move files.
  5. Enter renames files — Use ⌘ + O or ⌘ + ↓ to open them.
  6. Closing windows doesn't quit apps — Red X just closes the window. App stays in Dock.
  7. Path separator is / — Not backslash like Windows.

Trackpad Gestures Worth Learning

The MacBook trackpad is one of its best features. These gestures will boost your productivity:

GestureAction
Two-finger scrollScroll
Two-finger tapRight-click
Three-finger swipe upMission Control
Three-finger swipe left/rightSwitch Spaces/Desktops
Pinch with four fingersLaunchpad
Three-finger tapLook up word definition

Recommended System Settings

These settings will make your Mac feel much more responsive:

  • System Settings → Trackpad → Tap to click — Enable it
  • System Settings → Keyboard → Key Repeat — Set to fastest
  • System Settings → Keyboard → Delay Until Repeat — Set to shortest
  • Accessibility → Pointer Control → Trackpad Options → Dragging style — Three-finger drag

Quick Reference: The 15 Most Essential Shortcuts

ShortcutAction
⌘ + SpaceSpotlight (launch anything)
⌘ + TabSwitch apps
⌘ + `Switch windows of same app
⌘ + QQuit app
⌘ + WClose window/tab
⌘ + ,Preferences
⌘ + ⇧ + 4Screenshot selection
⌘ + ⇧ + .Show hidden files
⌃ + ⌘ + SpaceEmoji picker
⌃ + RSearch terminal history
⌃ + CKill process (Terminal)
⌘ + PQuick open (VS Code)
⌘ + ⇧ + PCommand palette
⌃ + `Toggle terminal
⌘ + ⌥ + IDevTools

Related Resources

Check out these other guides on our blog:

Need Help Setting Up Your Development Environment?

Whether you're transitioning from Windows or setting up a new MacBook for development, our team can help you configure your system for maximum productivity.

Contact WebPCDesigns

OneDrive Removal Suite - Production-Grade PowerShell Script

December 30, 2025 Updated May 29, 2026
powershell windows onedrive debloat removal system-administration

Overview

Production-grade PowerShell script for safely removing Microsoft OneDrive from Windows systems. Designed with safety, transparency, and user control.

Key Features

  • Safety First - Dual-confirmation system prevents accidental execution
  • Comprehensive Logging - All actions recorded for troubleshooting
  • Error Handling - Individual failures don't crash the process
  • Compatibility - PowerShell 3.0+ and Windows 7-11
  • Group Policy Support - Auto-generates remediation script for enterprise systems

System Requirements

  • OS: Windows 7, 8, 10, 11
  • PowerShell: Version 3.0 or higher
  • Permissions: Administrator (required)

What Gets Removed

Processes

OneDrive.exe
OneDriveStandaloneUpdater.exe

Folders & Registry

User profile OneDrive folder, temporary files, registry entries, and Shell integration

How to Use

# Method 1: Direct execution
.\OneDrive-Removal-Suite.ps1

# Method 2: With Bypass (if needed)
powershell -ExecutionPolicy Bypass -File ".\OneDrive-Removal-Suite.ps1"

Important Warnings

Group Policy Remediation

If your system has Group Policy controlling OneDrive:

  • Script automatically detects Group Policy settings
  • Auto-generates remediation script to remove policy constraints
  • Prevents automatic OneDrive reinstallation

Download & Verification

Complete package includes README, verification guide, and SHA256 checksums for file integrity.

Download OneDrive Removal Suite

Version History

v1.0 (December 30, 2025)

  • Full OneDrive removal functionality
  • Dual-confirmation system
  • Group Policy detection and remediation
  • Comprehensive logging
  • PowerShell 3.0+ compatibility
  • Windows 7-11 support

License

Feel free to share, modify, and distribute this script. Attribution appreciated.

Why You Might Want OneDrive Removed

OneDrive integrates deeply into Windows 10 and 11 — it hooks into File Explorer, syncs your Desktop and Documents folders, and runs background processes even when you're not actively using it. For power users, IT administrators managing fleets of PCs, or anyone who prefers a different cloud provider, removing it entirely is a reasonable choice. Common reasons include: reclaiming startup time, eliminating sync conflicts, reducing background disk I/O, and maintaining full local control over files.

The Manual Uninstall Method

Before running PowerShell, try the standard uninstall path first — Microsoft does provide one, though it's buried:

  1. Open Settings → Apps → Installed Apps
  2. Search for Microsoft OneDrive
  3. Click the three-dot menu → Uninstall

This works cleanly on Windows 11 22H2 and later. If it fails, is greyed out, or OneDrive reinstalls itself after a Windows Update, the PowerShell approach below is the reliable fallback.

Preventing OneDrive from Reinstalling

Windows Updates occasionally restore OneDrive. Block this with a Group Policy edit (works on Pro/Enterprise) or a registry key (works on all editions):

# Prevent OneDrive reinstall via registry (all Windows editions)
$regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive"
If (!(Test-Path $regPath)) { New-Item -Path $regPath -Force }
Set-ItemProperty -Path $regPath -Name "DisableFileSyncNGSC" -Value 1 -Type DWord

# Also prevent the setup experience from auto-launching
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" `
    -Name "OneDrive" -Value "" -ErrorAction SilentlyContinue

To apply via Group Policy on Pro/Enterprise: run gpedit.msc, navigate to Computer Configuration → Administrative Templates → Windows Components → OneDrive, and enable "Prevent the usage of OneDrive for file storage".

Redirecting Shell Folders Back to Local Paths

If OneDrive had backup of Desktop, Documents, or Pictures enabled, those folders may now point to C:\Users\YourName\OneDrive\Documents instead of the local path. Fix this after removal:

# Check current shell folder paths
$shell = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
Get-ItemProperty $shell | Select-Object Desktop, Personal, "{My Pictures}"

# Reset Documents to local path
$user = $env:USERNAME
Set-ItemProperty -Path $shell -Name "Personal" -Value "C:\Users\$user\Documents"
Set-ItemProperty -Path $shell -Name "Desktop"  -Value "C:\Users\$user\Desktop"

OneDrive Alternatives Worth Considering

Removing OneDrive doesn't mean giving up cloud sync. Alternatives that integrate well without Windows-level hooks include Nextcloud (self-hosted, full control), Syncthing (peer-to-peer, no cloud middleman), Google Drive for Desktop, and Backblaze for pure backup. For business users, Tresorit and ProtonDrive offer end-to-end encryption that OneDrive doesn't provide by default.

Troubleshooting Leftover Artifacts

After uninstall, OneDrive sometimes leaves behind registry keys, scheduled tasks, or a stubborn process. Clean these manually:

# Kill any running OneDrive process
Stop-Process -Name OneDrive -Force -ErrorAction SilentlyContinue

# Remove leftover scheduled tasks
Get-ScheduledTask | Where-Object { $_.TaskName -like "*OneDrive*" } | Unregister-ScheduledTask -Confirm:$false

# Clean up residual app data folders
Remove-Item "$env:LOCALAPPDATA\Microsoft\OneDrive" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item "$env:PROGRAMDATA\Microsoft OneDrive" -Recurse -Force -ErrorAction SilentlyContinue

Frequently Asked Questions

Will removing OneDrive delete my files?
No — uninstalling OneDrive only removes the sync client. Files already synced to your local drive remain untouched. Files stored only in the cloud will need to be downloaded first.
Does this work on Windows 11?
Yes, the PowerShell commands above work on Windows 10 and 11. Windows 11 made the GUI uninstall easier, so try that path first.
Can I reinstall OneDrive later?
Yes — download the latest installer from microsoft.com at any time. Undo the registry policy key first if you added it.

Nginx VPS Configuration & Optimization Commands

December 17, 2025 Updated May 29, 2026
ubuntu nginx web-server vps ssl optimization

Nginx Management Essentials

Essential commands for managing Nginx on Ubuntu VPS. These snippets cover installation, SSL setup, performance tuning, and troubleshooting.

1. Complete Nginx Installation & Setup

Install Nginx and enable it to start on boot:

# Install Nginx
sudo apt update && sudo apt install nginx -y

# Enable and start Nginx
sudo systemctl enable nginx
sudo systemctl start nginx

# Check status
sudo systemctl status nginx

# Test Nginx configuration
sudo nginx -t

2. SSL Certificate with Let's Encrypt

Set up free SSL certificates using Certbot:

# Install Certbot
sudo apt install certbot python3-certbot-nginx -y

# Obtain and install SSL certificate
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Auto-renewal test
sudo certbot renew --dry-run

# List all certificates
sudo certbot certificates

3. View Real-Time Access Logs

Monitor incoming requests in real-time:

# Tail access log with color coding
sudo tail -f /var/log/nginx/access.log

# Show only 403/404/500 errors
sudo tail -f /var/log/nginx/access.log | grep -E "403|404|500"

# Monitor specific domain
sudo tail -f /var/log/nginx/access.log | grep "yourdomain.com"

# Count requests per IP in last 1000 lines
sudo tail -1000 /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -20

Best Practices

  • Always test configuration with nginx -t before reloading
  • Keep SSL certificates updated - check certbot renew regularly
  • Monitor error logs daily for security issues
  • Use nginx -s reload instead of restart for zero-downtime config updates
  • Implement rate limiting on all public endpoints
  • Set up log rotation to prevent disk space issues

Enabling Gzip Compression in Nginx

Gzip compression dramatically reduces the size of text-based responses sent over the wire, improving load times and reducing bandwidth costs. Add the following block inside your http context in /etc/nginx/nginx.conf:

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json
           application/javascript application/xml+rss
           application/atom+xml image/svg+xml;

Run nginx -t && systemctl reload nginx after every config change. Verify compression is active with curl -H "Accept-Encoding: gzip" -I https://yourdomain.com and look for Content-Encoding: gzip in the response headers.

Browser Caching with Cache-Control Headers

Static assets — images, CSS, JavaScript — rarely change between requests. Telling browsers to cache them locally saves round-trips and speeds up repeat visits significantly.

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

Use a content-hash in filenames (e.g. app.a3f9c1.js) so browsers pick up new versions automatically when you deploy.

Rate Limiting to Prevent Abuse

Rate limiting protects your server from brute-force attacks, scrapers, and runaway clients. Define a shared memory zone and apply it to sensitive endpoints:

http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
}

server {
    location /login {
        limit_req zone=login burst=3 nodelay;
    }
}

The burst parameter allows a small spike above the rate before nginx starts returning 429 Too Many Requests. Monitor hits with grep "limiting requests" /var/log/nginx/error.log.

Hardening Security Headers

Security headers are free to add and meaningfully reduce your attack surface. Place these inside your server block or a shared snippet:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Validate your headers at securityheaders.com — aim for an A or A+ rating.

Tuning Worker Processes and Connections

Nginx performance at the OS level is controlled by a few key directives in /etc/nginx/nginx.conf:

worker_processes auto;          # match CPU core count
worker_rlimit_nofile 65535;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    keepalive_timeout 65;
    keepalive_requests 1000;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
}

worker_processes auto automatically sets one worker per CPU core. sendfile enables zero-copy file transfers. tcp_nopush batches response headers with the first data packet, reducing small-packet overhead.

Testing Your Configuration

Always validate before reloading: nginx -t catches syntax errors without touching the live config. Use ab (Apache Bench) or wrk for load testing:

wrk -t4 -c100 -d30s https://yourdomain.com/

Check /var/log/nginx/access.log and error.log regularly. Tools like GoAccess parse nginx logs in real time and produce useful dashboards without sending data to third parties.

PowerShell 7 Advanced System Administration Commands

December 17, 2025 Updated May 29, 2026
powershell windows system-admin automation scripting

PowerShell 7 Core Concepts

PowerShell 7 is cross-platform and packed with powerful cmdlets for system administration. These snippets work on Windows, Linux, and macOS.

1. System Information Gathering

Get comprehensive system information:

# Detailed system info
Get-ComputerInfo | Select-Object CsName, OsArchitecture, OsVersion, CsTotalPhysicalMemory

# CPU and memory usage
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU, WorkingSet

# Disk space analysis
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{N="Used(GB)";E={[math]::Round($_.Used/1GB,2)}}, @{N="Free(GB)";E={[math]::Round($_.Free/1GB,2)}}

2. Service Management

Manage Windows services with filtering and automation:

# List all running services
Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object Name, DisplayName, StartType

# Stop and disable a service
Stop-Service -Name "ServiceName" -Force
Set-Service -Name "ServiceName" -StartupType Disabled

# Restart multiple services
$services = @("Service1", "Service2", "Service3")
$services | ForEach-Object { Restart-Service -Name $_ -Force }

Network Administration

3. Advanced Network Diagnostics

PowerShell network troubleshooting commands:

# Get all network adapters with IP config
Get-NetIPAddress | Select-Object InterfaceAlias, IPAddress, PrefixLength

# Test connectivity with detailed output
Test-NetConnection -ComputerName google.com -InformationLevel Detailed

# Get active TCP connections
Get-NetTCPConnection | Where-Object {$_.State -eq "Established"} | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State

Automation Tips

  • Save frequently used scripts as .ps1 files in your scripts directory
  • Use PowerShell profiles to load custom functions on startup
  • Leverage -WhatIf parameter to test commands before execution
  • Create scheduled tasks with Register-ScheduledTask for automation
  • Use error handling with try/catch blocks in production scripts

File System Operations at Scale

PowerShell's pipeline makes bulk file operations far more powerful than anything you can do in File Explorer. Get-ChildItem, combined with Where-Object and ForEach-Object, handles thousands of files cleanly:

# Find files over 500 MB modified in the last 30 days
Get-ChildItem C:\Data -Recurse -File |
    Where-Object { $_.Length -gt 500MB -and $_.LastWriteTime -gt (Get-Date).AddDays(-30) } |
    Select-Object FullName, @{n='SizeMB';e={[math]::Round($_.Length/1MB,1)}} |
    Sort-Object SizeMB -Descending

# Bulk rename — add date prefix
Get-ChildItem C:\Reports\*.pdf | Rename-Item -NewName { "2026_$($_.Name)" }

Querying the Windows Event Log

The Windows Event Viewer GUI is slow for bulk analysis. PowerShell's Get-WinEvent is orders of magnitude faster and scriptable:

# Last 50 critical and error events from System log
Get-WinEvent -LogName System -MaxEvents 200 |
    Where-Object { $_.LevelDisplayName -in 'Critical','Error' } |
    Select-Object TimeCreated, Id, Message |
    Format-Table -AutoSize

# Failed logon attempts (Security log, Event ID 4625)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddHours(-24)} |
    Select-Object TimeCreated, @{n='User';e={$_.Properties[5].Value}},
                  @{n='IP';e={$_.Properties[19].Value}}

Local User and Group Management

Managing local accounts without leaving the terminal keeps workflows scriptable and auditable:

# List local users and whether they're enabled
Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet

# Create a restricted service account
$pw = ConvertTo-SecureString "Str0ng!Pass" -AsPlainText -Force
New-LocalUser "svc_backup" -Password $pw -FullName "Backup Service" -Description "Runs nightly backup"
Add-LocalGroupMember -Group "Backup Operators" -Member "svc_backup"

# Disable a stale account
Disable-LocalUser -Name "old.employee"

Scheduled Tasks via PowerShell

The ScheduledTasks module provides full control over the Task Scheduler from the command line — no GUI needed:

# List all tasks and their last run result
Get-ScheduledTask | Get-ScheduledTaskInfo |
    Select-Object TaskName, LastRunTime, LastTaskResult |
    Where-Object { $_.LastTaskResult -ne 0 }   # non-zero = error

# Create a daily maintenance task
$action  = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-File C:\Scripts\cleanup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 2am
$settings = New-ScheduledTaskSettingsSet -RunOnlyIfIdle:$false -StartWhenAvailable
Register-ScheduledTask "DailyCleanup" -Action $action -Trigger $trigger -Settings $settings -RunLevel Highest

Registry Operations

PowerShell treats the registry as a drive — you can navigate and modify it with the same verbs used for files:

# Read a value
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" -Name ProgramFilesDir

# Set a DWORD to disable a feature
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" `
    -Name "HideFileExt" -Value 0 -Type DWord

# Export a key subtree for backup before editing
reg export "HKCU\Software\MyApp" C:\Backups\myapp_reg_$(Get-Date -f yyyyMMdd).reg

Always export the key before modifying it in production. Registry mistakes can prevent Windows from booting — treat it with the same respect you would a production database.

Essential Ubuntu System Monitoring & Cleanup Commands

December 17, 2025 Updated May 29, 2026
ubuntu bash system-admin monitoring cleanup performance

Comprehensive System Monitoring

Check system resources, disk usage, and running processes with these essential Ubuntu commands. Perfect for diagnosing performance issues on your VPS or local machine.

1. Real-Time System Resource Monitor

Monitor CPU, memory, and processes in real-time with htop (more user-friendly than top):

sudo apt install htop -y && htop

2. Disk Usage Analysis

Find the largest directories consuming disk space:

# Show top 10 largest directories in /
sudo du -h / 2>/dev/null | sort -rh | head -n 10

# Or use ncdu for interactive browsing
sudo apt install ncdu -y
sudo ncdu /

3. Memory Usage Breakdown

View detailed memory usage including cache and buffers:

# Detailed memory info
free -h

# Show top memory-consuming processes
ps aux --sort=-%mem | head -n 10

System Cleanup Commands

4. Complete Package Cleanup

Remove unnecessary packages, clean apt cache, and reclaim disk space:

# Full cleanup chain
sudo apt autoremove -y && \
sudo apt autoclean -y && \
sudo apt clean -y && \
sudo journalctl --vacuum-time=3d && \
sudo rm -rf /tmp/* 2>/dev/null

echo "Cleanup complete!"

5. Find and Remove Old Kernels

Safely remove old kernel versions (keep current + 1 previous):

# List installed kernels
dpkg --list | grep linux-image

# Remove old kernels (interactive)
sudo apt autoremove --purge

6. Clear System Logs

Reduce systemd journal size and clear old logs:

# Limit journal to 100MB
sudo journalctl --vacuum-size=100M

# Keep only last 2 days of logs
sudo journalctl --vacuum-time=2d

# Check current journal size
journalctl --disk-usage

Performance Monitoring

7. Check Network Connections

View active network connections and listening ports:

# Show all listening ports
sudo netstat -tulpn | grep LISTEN

# Or use ss (faster, modern alternative)
sudo ss -tulpn | grep LISTEN

# Monitor real-time network usage
sudo apt install nethogs -y && sudo nethogs

8. Service Status Check

Check status of critical services:

# Check multiple services at once
for service in nginx postgresql ssh ufw; do
    systemctl is-active $service && \
    echo "✓ $service is running" || \
    echo "✗ $service is NOT running"
done

Pro Tips

  • Run cleanup commands monthly or when disk space is low
  • Always use sudo for system-level operations
  • Create aliases in ~/.bashrc for frequently used commands
  • Monitor systemd journal size - it can grow to several GB on busy servers

Analyzing Systemd Service Startup Times

systemd-analyze reveals exactly how long boot took and which services are responsible for the slowdown:

# Total boot time breakdown
systemd-analyze

# Per-service time sorted by slowest
systemd-analyze blame | head -20

# Visual SVG timeline (opens in browser)
systemd-analyze plot > /tmp/boot.svg

Services taking more than 3–5 seconds are candidates for disabling (if you don't need them) or masking. Disable with systemctl disable --now servicename. Common culprits on VPS servers: ModemManager, avahi-daemon, and multipathd.

Swap Management and Tuning

On systems with adequate RAM, swap should rarely be used. A high vm.swappiness value causes the kernel to swap aggressively, degrading performance:

# Check current swap usage
free -h && swapon --show

# Check swappiness (default is 60, server-optimal is 10)
cat /proc/sys/vm/swappiness

# Set it permanently
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

If your server has 2 GB+ RAM and swap is consistently in use, the real fix is identifying the memory-hungry process with ps aux --sort=-%mem | head -10, not expanding swap.

Log Rotation and Journal Size Control

Systemd journals can grow unchecked on busy servers. Cap them to prevent disk fill:

# Check current journal size
journalctl --disk-usage

# Vacuum entries older than 30 days OR down to 500 MB
sudo journalctl --vacuum-time=30d
sudo journalctl --vacuum-size=500M

# Make the cap permanent
sudo nano /etc/systemd/journald.conf
# Set: SystemMaxUse=500M and MaxRetentionSec=1month
sudo systemctl restart systemd-journald

For traditional syslog (/var/log/), logrotate handles rotation. Check /etc/logrotate.d/ for per-service configs and logrotate -d /etc/logrotate.conf to do a dry run.

Fail2Ban: Automatic Brute-Force Protection

Fail2ban monitors logs and temporarily bans IPs that show malicious behavior — essential for any server with SSH exposed to the internet:

# Install and enable
sudo apt install fail2ban -y
sudo systemctl enable --now fail2ban

# Check banned IPs
sudo fail2ban-client status sshd

# Unban a specific IP (if you lock yourself out)
sudo fail2ban-client set sshd unbanip 1.2.3.4

Create /etc/fail2ban/jail.local to override defaults without touching jail.conf (which gets overwritten on updates). Recommended SSH settings: maxretry = 3, bantime = 1h, findtime = 10m.

Docker and Container Cleanup

If you run Docker, images, containers, and volumes accumulate silently. A full prune recovers significant disk space:

# What's taking space?
docker system df

# Remove stopped containers, dangling images, unused networks
docker system prune -f

# Also remove unused volumes (careful — this deletes data)
docker system prune --volumes -f

# Remove all unused images (not just dangling)
docker image prune -a -f

Schedule a weekly prune with cron: 0 3 * * 0 /usr/bin/docker system prune -f >> /var/log/docker-prune.log 2>&1