How to list block devices/UUIDs → lsblk -f; blkid

How to List Block Devices and UUIDs Using lsblk -f and blkid Commands Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding Block Devices and UUIDs](#understanding-block-devices-and-uuids) 4. [Using lsblk Command](#using-lsblk-command) 5. [Using blkid Command](#using-blkid-command) 6. [Practical Examples and Use Cases](#practical-examples-and-use-cases) 7. [Advanced Usage and Options](#advanced-usage-and-options) 8. [Troubleshooting Common Issues](#troubleshooting-common-issues) 9. [Best Practices and Professional Tips](#best-practices-and-professional-tips) 10. [Conclusion](#conclusion) Introduction Managing storage devices in Linux systems requires a thorough understanding of block devices and their unique identifiers. Whether you're a system administrator configuring mount points, a developer working with storage solutions, or a Linux enthusiast exploring system internals, knowing how to list and identify block devices is essential. This comprehensive guide will teach you how to effectively use two powerful Linux commands: `lsblk -f` and `blkid`. These tools provide detailed information about block devices, including their UUIDs (Universally Unique Identifiers), file systems, labels, and mount points. By the end of this article, you'll master these commands and understand when and how to use each one for different scenarios. Prerequisites Before diving into the commands, ensure you have: - A Linux system (any distribution) - Basic command-line knowledge - Terminal or SSH access to your system - Root or sudo privileges for certain operations - At least one storage device (hard drive, SSD, USB drive, etc.) Software Requirements: - `util-linux` package (contains lsblk) - `util-linux` or `e2fsprogs` package (contains blkid) Most Linux distributions include these packages by default. If not, install them using your distribution's package manager. Understanding Block Devices and UUIDs What Are Block Devices? Block devices are storage devices that handle data in fixed-size blocks, typically 512 bytes or 4KB. Common examples include: - Hard disk drives (HDDs) - Solid-state drives (SSDs) - USB flash drives - SD cards - CD/DVD drives - Network block devices - Loop devices In Linux, block devices appear as files in the `/dev` directory with names like `/dev/sda`, `/dev/nvme0n1`, or `/dev/mmcblk0`. Understanding UUIDs A UUID (Universally Unique Identifier) is a 128-bit identifier that uniquely identifies a file system or partition. UUIDs are crucial because: - Device names (like `/dev/sda1`) can change between reboots - UUIDs remain constant regardless of device connection order - They're essential for reliable `/etc/fstab` entries - They prevent mounting wrong partitions in automated systems Example UUID format: `550e8400-e29b-41d4-a716-446655440000` Using lsblk Command Basic lsblk Usage The `lsblk` command displays block devices in a tree format, showing the relationship between devices and their partitions. ```bash lsblk ``` Sample Output: ``` NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 500G 0 disk ├─sda1 8:1 0 512M 0 part /boot/efi ├─sda2 8:2 0 1G 0 part /boot └─sda3 8:3 0 498G 0 part / sdb 8:16 0 1T 0 disk └─sdb1 8:17 0 1T 0 part /home ``` Using lsblk -f for File System Information The `-f` option displays file system information, including UUIDs, labels, and file system types: ```bash lsblk -f ``` Sample Output: ``` NAME FSTYPE LABEL UUID FSAVAIL FSUSE% MOUNTPOINT sda ├─sda1 vfat EFI 12AB-34CD 510M 0% /boot/efi ├─sda2 ext4 BOOT 550e8400-e29b-41d4-a716-446655440000 900M 10% /boot └─sda3 ext4 ROOT a1b2c3d4-e5f6-7890-abcd-ef1234567890 450G 15% / sdb └─sdb1 ext4 HOME fedcba98-7654-3210-fedc-ba9876543210 900G 10% /home ``` Key Information Provided by lsblk -f - NAME: Device or partition name - FSTYPE: File system type (ext4, ntfs, vfat, etc.) - LABEL: User-defined label for the file system - UUID: Unique identifier for the file system - FSAVAIL: Available space on mounted file systems - FSUSE%: Percentage of used space - MOUNTPOINT: Where the device is mounted in the directory tree Additional lsblk Options ```bash Show all devices including empty ones lsblk -f -a Display output in JSON format lsblk -f -J Show specific columns lsblk -f -o NAME,FSTYPE,UUID,MOUNTPOINT Display sizes in human-readable format lsblk -f -h ``` Using blkid Command Basic blkid Usage The `blkid` command is specifically designed to locate and print block device attributes, focusing on UUIDs and file system information. ```bash blkid ``` Sample Output: ``` /dev/sda1: UUID="12AB-34CD" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="12345678-1234-1234-1234-123456789abc" /dev/sda2: UUID="550e8400-e29b-41d4-a716-446655440000" TYPE="ext4" PARTUUID="87654321-4321-4321-4321-cba987654321" /dev/sda3: UUID="a1b2c3d4-e5f6-7890-abcd-ef1234567890" TYPE="ext4" PARTUUID="abcdef12-3456-7890-abcd-ef1234567890" /dev/sdb1: LABEL="HOME" UUID="fedcba98-7654-3210-fedc-ba9876543210" TYPE="ext4" PARTUUID="11111111-2222-3333-4444-555555555555" ``` Querying Specific Devices ```bash Get information about a specific device blkid /dev/sda1 Get information about multiple devices blkid /dev/sda1 /dev/sda2 /dev/sdb1 ``` Filtering by Attributes ```bash Find device by UUID blkid -U 550e8400-e29b-41d4-a716-446655440000 Find device by label blkid -L "HOME" Find devices by file system type blkid -t TYPE=ext4 Find devices by label pattern blkid -t LABEL="BACKUP*" ``` Output Formatting Options ```bash Display only UUIDs blkid -s UUID Display only file system types blkid -s TYPE Display specific attributes blkid -s UUID -s TYPE -s LABEL Output without device names blkid -s UUID -o value /dev/sda1 ``` Practical Examples and Use Cases Example 1: Preparing fstab Entries When configuring automatic mounting in `/etc/fstab`, UUIDs are preferred over device names: ```bash Get UUID for a partition blkid -s UUID -o value /dev/sda3 Or use lsblk to see the complete picture lsblk -f /dev/sda ``` fstab entry example: ``` UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890 / ext4 defaults 0 1 ``` Example 2: Identifying New USB Drives When a USB drive is connected, identify it quickly: ```bash Before connecting USB drive lsblk -f > /tmp/before.txt After connecting USB drive lsblk -f > /tmp/after.txt Compare to see the new device diff /tmp/before.txt /tmp/after.txt ``` Example 3: Backup Script Integration Use these commands in backup scripts to verify target devices: ```bash #!/bin/bash BACKUP_UUID="fedcba98-7654-3210-fedc-ba9876543210" BACKUP_DEVICE=$(blkid -U $BACKUP_UUID) if [ -n "$BACKUP_DEVICE" ]; then echo "Backup device found: $BACKUP_DEVICE" # Proceed with backup else echo "Backup device not found!" exit 1 fi ``` Example 4: System Inventory Create a comprehensive storage inventory: ```bash #!/bin/bash echo "=== Block Device Inventory ===" echo "Date: $(date)" echo "" echo "=== Device Tree ===" lsblk -f echo "" echo "=== Detailed Device Information ===" blkid echo "" echo "=== Disk Usage ===" df -h ``` Example 5: Monitoring File System Changes Track file system modifications: ```bash Create baseline blkid > /var/log/blkid-baseline.txt Check for changes (run periodically) blkid > /tmp/blkid-current.txt if ! diff -q /var/log/blkid-baseline.txt /tmp/blkid-current.txt > /dev/null; then echo "Block device configuration changed!" diff /var/log/blkid-baseline.txt /tmp/blkid-current.txt fi ``` Advanced Usage and Options Advanced lsblk Options ```bash Show device topology lsblk -f -T Include loop devices lsblk -f -a Show device dependencies lsblk -f -D Custom column selection lsblk -f -o NAME,FSTYPE,UUID,SIZE,MOUNTPOINT,FSAVAIL,FSUSE% Show device serial numbers and models lsblk -f -o NAME,FSTYPE,UUID,SERIAL,MODEL Display in list format instead of tree lsblk -f -l ``` Advanced blkid Options ```bash Probe specific file system types only blkid -t TYPE=ext4 Use alternative cache file blkid -c /tmp/blkid.cache Disable cache usage (force fresh probe) blkid -c /dev/null Show all attributes blkid -o full Export format suitable for shell evaluation blkid -o export /dev/sda1 Low-level probe (requires root) sudo blkid -p /dev/sda1 ``` Combining Commands for Complex Queries ```bash Find all ext4 partitions and their mount points lsblk -f -l | grep ext4 Get UUIDs of all mounted ext4 file systems blkid -t TYPE=ext4 | grep -E "$(mount | grep ext4 | cut -d' ' -f1 | tr '\n' '|' | sed 's/|$//')" List unmounted file systems comm -23 <(blkid -o device | sort) <(mount | cut -d' ' -f1 | sort) ``` Troubleshooting Common Issues Issue 1: Command Not Found Problem: `lsblk: command not found` or `blkid: command not found` Solution: ```bash For Debian/Ubuntu sudo apt update && sudo apt install util-linux For RHEL/CentOS/Fedora sudo yum install util-linux or sudo dnf install util-linux For Arch Linux sudo pacman -S util-linux ``` Issue 2: Permission Denied Problem: Cannot access certain device information Solution: ```bash Run with sudo for complete information sudo lsblk -f sudo blkid Add user to disk group (logout/login required) sudo usermod -a -G disk $USER ``` Issue 3: Outdated Cache Information Problem: `blkid` shows outdated information Solution: ```bash Clear blkid cache sudo blkid -g Force fresh probe sudo blkid -c /dev/null Update cache sudo blkid ``` Issue 4: Missing UUID Information Problem: No UUID displayed for a device Possible Causes and Solutions: ```bash Check if device has a file system sudo file -s /dev/sdX1 Create file system if needed sudo mkfs.ext4 /dev/sdX1 For swap partitions sudo mkswap /dev/sdX1 Refresh device information sudo partprobe /dev/sdX ``` Issue 5: Inconsistent Device Names Problem: Device names change between reboots Solution: Always use UUIDs in configuration files: ```bash Instead of using device names in fstab /dev/sdb1 /home ext4 defaults 0 2 Use UUIDs UUID=fedcba98-7654-3210-fedc-ba9876543210 /home ext4 defaults 0 2 ``` Issue 6: Loop Devices Not Showing Problem: Loop devices or other special devices not visible Solution: ```bash Show all devices including empty ones lsblk -f -a Include specific device types lsblk -f -I 7 # Show only loop devices (major number 7) ``` Best Practices and Professional Tips 1. Regular System Monitoring Create monitoring scripts that track block device changes: ```bash #!/bin/bash /usr/local/bin/check-block-devices.sh LOG_FILE="/var/log/block-device-changes.log" BASELINE="/var/lib/block-device-baseline.txt" if [ ! -f "$BASELINE" ]; then lsblk -f -P > "$BASELINE" echo "$(date): Baseline created" >> "$LOG_FILE" exit 0 fi CURRENT=$(mktemp) lsblk -f -P > "$CURRENT" if ! diff -q "$BASELINE" "$CURRENT" > /dev/null; then echo "$(date): Block device configuration changed" >> "$LOG_FILE" diff "$BASELINE" "$CURRENT" >> "$LOG_FILE" cp "$CURRENT" "$BASELINE" fi rm "$CURRENT" ``` 2. Documentation and Inventory Maintain comprehensive documentation: ```bash #!/bin/bash Generate system storage report REPORT_FILE="/var/log/storage-report-$(date +%Y%m%d).txt" { echo "=== Storage Report Generated: $(date) ===" echo "" echo "=== Block Device Tree ===" lsblk -f echo "" echo "=== All Block Device Attributes ===" blkid echo "" echo "=== Mount Points and Usage ===" df -h echo "" echo "=== Disk I/O Statistics ===" iostat -x 1 1 2>/dev/null || echo "iostat not available" } > "$REPORT_FILE" echo "Storage report generated: $REPORT_FILE" ``` 3. Automated Backup Verification Verify backup devices before starting backups: ```bash #!/bin/bash verify_backup_device() { local expected_uuid="$1" local mount_point="$2" # Check if device exists local device=$(blkid -U "$expected_uuid") if [ -z "$device" ]; then echo "ERROR: Backup device with UUID $expected_uuid not found" return 1 fi # Check if mounted at expected location local current_mount=$(lsblk -f -n -o MOUNTPOINT "$device" | tr -d ' ') if [ "$current_mount" != "$mount_point" ]; then echo "ERROR: Device $device not mounted at $mount_point" return 1 fi # Check available space local available=$(df --output=avail "$mount_point" | tail -n1) if [ "$available" -lt 1048576 ]; then # Less than 1GB echo "WARNING: Low disk space on backup device" fi echo "Backup device verification successful" return 0 } ``` 4. Safe Device Operations Always verify device identity before operations: ```bash #!/bin/bash safe_format_device() { local device="$1" local expected_size="$2" # in GB # Verify device exists if [ ! -b "$device" ]; then echo "ERROR: $device is not a block device" return 1 fi # Check size local actual_size=$(lsblk -b -n -o SIZE "$device") local expected_bytes=$((expected_size 1024 1024 * 1024)) if [ "$actual_size" -ne "$expected_bytes" ]; then echo "ERROR: Device size mismatch" echo "Expected: $expected_size GB" echo "Actual: $((actual_size / 1024 / 1024 / 1024)) GB" return 1 fi # Show device information for final confirmation echo "Device information:" lsblk -f "$device" echo "" read -p "Are you sure you want to format $device? (yes/no): " confirm if [ "$confirm" = "yes" ]; then sudo mkfs.ext4 "$device" else echo "Operation cancelled" fi } ``` 5. Performance Considerations - Use `lsblk` for quick overviews and tree structures - Use `blkid` for specific UUID lookups and script automation - Cache blkid results in scripts to avoid repeated probing - Use `-c /dev/null` with blkid only when fresh data is essential 6. Security Considerations ```bash Limit access to sensitive device information sudo chmod 750 /usr/local/bin/device-scripts/ Log all device operations exec 1> >(logger -s -t $(basename $0)) 2>&1 Validate input in scripts validate_uuid() { local uuid="$1" if [[ ! "$uuid" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then echo "Invalid UUID format" return 1 fi } ``` Conclusion Mastering the `lsblk -f` and `blkid` commands is essential for effective Linux system administration. These powerful tools provide comprehensive information about block devices, file systems, and their unique identifiers, enabling you to: - Reliably identify storage devices using UUIDs - Create robust fstab entries that survive system changes - Develop automated scripts for storage management - Troubleshoot storage-related issues efficiently - Maintain comprehensive system documentation Key Takeaways: 1. Use lsblk -f when you need a visual tree representation of devices and their relationships, along with file system information and mount points. 2. Use blkid when you need specific device attributes, UUID lookups, or when scripting automated storage operations. 3. Always prefer UUIDs over device names in configuration files and scripts to ensure reliability across reboots and hardware changes. 4. Implement proper error handling in scripts that depend on device identification to prevent data loss or system issues. 5. Regular monitoring of block device changes helps maintain system security and prevents unexpected issues. By incorporating these commands into your regular Linux workflow and following the best practices outlined in this guide, you'll be well-equipped to handle complex storage scenarios with confidence. Whether you're managing a single-user desktop or a complex multi-server environment, these skills form the foundation of reliable storage management in Linux systems. Remember to always test your scripts and procedures in safe environments before applying them to production systems, and maintain current backups of critical data before performing any storage operations.