0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

Disk, Filesystem, and Mount Automation

Inspect block devices, manage fstab entries, and script LVM and mount operations safely.

Understanding Block Devices with lsblk and fdisk

Before automating disk operations, you must be able to inspect what block devices exist on the system. Two essential tools are lsblk and fdisk -l.

  • lsblk — lists block devices in a tree format showing device names, sizes, mount points, and types (disk, part, lvm)
  • fdisk -l — shows partition tables and sector details (requires root)
  • blkid — prints UUIDs and filesystem types for each block device

In scripts, you will often need to parse this output to detect available disks, check if a partition is formatted, or determine its UUID before mounting.

#!/usr/bin/env bash
# Inspect all block devices and their UUIDs
set -euo pipefail

echo '=== Block Device Tree ==='
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT,UUID

echo ''
echo '=== Partition Table Details ==='
sudo fdisk -l 2>/dev/null | grep -E '^Disk |^/dev/'

echo ''
echo '=== UUID Lookup via blkid ==='
sudo blkid | awk -F: '{print $1}' | while read -r dev; do
  uuid=$(sudo blkid -s UUID -o value "$dev" 2>/dev/null || echo 'N/A')
  fstype=$(sudo blkid -s TYPE -o value "$dev" 2>/dev/null || echo 'unknown')
  printf '%-20s UUID=%-38s TYPE=%s\n' "$dev" "$uuid" "$fstype"
done

Checking Disk Space with df and du

df and du are the workhorses for reporting filesystem and directory usage. In sysadmin scripts, you use them to trigger alerts, enforce quotas, or decide when to provision more space.

  • df -h — human-readable filesystem usage across all mounted filesystems
  • df -BG — output in gigabytes for consistent numeric parsing
  • du -sh /path — summarized size of a specific directory
  • du -d 1 /var — one-level deep breakdown (useful to find which subdirectory is large)

The percent used column from df is commonly parsed to fire disk-full alerts in monitoring scripts.

#!/usr/bin/env bash
# Alert if any mounted filesystem exceeds a usage threshold
set -euo pipefail

THRESHOLD=80   # percent

echo 'Checking filesystem usage...'
df -h --output=source,pcent,target | tail -n +2 | while IFS= read -r line; do
  device=$(awk '{print $1}' <<< "$line")
  pct=$(awk '{print $2}' <<< "$line" | tr -d '%')
  mount=$(awk '{print $3}' <<< "$line")

  # Skip pseudo filesystems
  [[ "$device" == tmpfs* || "$device" == devtmpfs* ]] && continue

  if (( pct >= THRESHOLD )); then
    echo "WARNING: $device mounted at $mount is ${pct}% full" >&2
  else
    echo "OK: $device at $mount is ${pct}% used"
  fi
done

All lessons in this course

  1. Automating User and Group Provisioning
  2. Controlling systemd Services and Writing Unit Files
  3. Disk, Filesystem, and Mount Automation
  4. Building System Health Check and Alert Scripts
← Back to Linux Command Line & Bash Scripting Mastery