The Art of Mounting, Finding, and Locating Data
We've mastered the logical structure of the Filesystem Hierarchy Standard (FHS). Now, we dive deeper to understand the physical reality that underpins it. A Linux system is a master of abstraction, presenting a single, unified directory tree (/) to the user. Behind the scenes, this tree is composed of multiple physical devices, partitions, and network shares, all seamlessly grafted together. This module covers the essential skills for managing this connection: identifying and mounting file systems, and the powerful tools used to find any file, anywhere on the system.
The Foundation: File Systems and Block Devices
Before you can mount a device, you must understand what it is and how Linux sees it.
Block Devices
At its core, a block device is a hardware component designed to store data in fixed-size blocks (e.g., 512 bytes, 4KB). Think of hard disk drives (HDDs), solid-state drives (SSDs), USB drives, and even CD/DVD-ROMs. In Linux, these devices are abstractly represented as special files located within the /dev directory.
/dev/sda,/dev/sdb, etc.: These typically refer to entire physical hard drives.sdais usually the first drive detected,sdbthe second, and so on. The 'sd' prefix stands for SCSI Disk, a legacy term that now applies to most modern storage interfaces like SATA, SAS, and USB./dev/sda1,/dev/sdb2, etc.: These denote specific partitions on a drive.sda1is the first partition on thesdadrive,sdb2is the second partition on thesdbdrive. Partitions allow a single physical disk to be divided into multiple independent storage areas./dev/sr0,/dev/cdrom: These often refer to optical drives like CD/DVD/Blu-ray ROMs.
File Systems
A raw block device is just a blank canvas. To make it usable for storing files, it needs a file system. A file system is essentially a highly organized structure and a set of rules (an "operating manual") that tells the kernel how to manage files, directories, metadata (like permissions, ownership, timestamps), and free space on that block device. Without a file system, the block device is just a collection of unaddressable blocks of data.
- XFS: The default and highly recommended file system for CentOS/RHEL. It's known for its high performance, scalability (can handle very large filesystems), and robust journaling capabilities. Journaling helps maintain data integrity by recording changes before they are committed to the main filesystem, making recovery from unexpected shutdowns much faster and safer.
- ext4 (Fourth Extended Filesystem): A very common and mature file system on Linux, often the default on Debian/Ubuntu systems. It's a successor to ext3 and ext2, offering improved performance, larger file size support, and journaling.
- FAT32/NTFS: Often used for interoperability with Windows systems, especially for USB drives.
- NFS (Network File System): Not a local file system type, but a protocol to mount remote file systems over a network.
Inspecting Block Devices with `lsblk`
The lsblk (List Block Devices) command is your go-to tool for a clear, tree-like overview of your storage devices and how they're currently mounted. It shows you the relationships between disks, partitions, and their mount points.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 30G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 29G 0 part /
sr0 11:0 1 1024M 0 rom
sdb 8:16 0 50G 0 disk
└─sdb1 8:17 0 50G 0 part /dataNAME: The device name (e.g., sda, sda1, sdb, sdb1, sr0).
MAJ:MIN: Major and Minor device numbers, used internally by the kernel to identify devices.
RM: Removable device (1 for removable, 0 for fixed).
SIZE: The size of the device or partition.
RO: Read-only device (1 for read-only, 0 for read-write).
TYPE: Device type (disk, part for partition, rom for CD-ROM, lvm for LVM logical volume).
MOUNTPOINT: Where the device is currently mounted in the filesystem hierarchy. If blank, it means the device or partition is not currently mounted.
From the example above, we can see sda is a 30GB disk with two partitions: sda1 mounted at /boot and sda2 mounted at the root (/). We also see sdb, a 50GB disk with one partition sdb1, which is mounted at /data.
Identifying File Systems with `df -hT`
While lsblk shows block devices, df -hT (disk free, human-readable, type) focuses on *mounted file systems*, showing their type, size, and usage.
$ df -hT
Filesystem Type Size Used Avail Use% Mounted on
devtmpfs devtmpfs 4.0M 0 4.0M 0% /dev
tmpfs tmpfs 964M 0 964M 0% /dev/shm
tmpfs tmpfs 386M 9.1M 377M 3% /run
/dev/sda2 xfs 29G 5.7G 24G 20% /
/dev/sda1 xfs 997M 210M 788M 22% /boot
/dev/sdb1 xfs 50G 33M 50G 1% /data
tmpfs tmpfs 964M 4.0K 964M 1% /tmp
/dev/sr0 iso9660 4.3G 4.3G 0 100% /run/media/user/MyDiscThis output clearly shows the file system type (e.g., xfs, iso9660) for each mounted device, along with its capacity, used space, available space, and percentage used.
Mounting: Connecting Devices to the Filesystem Tree
Mounting is the fundamental operation that makes the contents of a block device's file system accessible within the Linux directory hierarchy. It's like grafting a new branch onto a tree. The point where this branch connects to the main tree is called the mount point, which must be an existing, empty directory.
Analogy: Imagine your main filesystem (/) as a vast, meticulously organized library building. A new hard drive (with its file system) is a new, complete collection of books, neatly cataloged within its own box. Mounting is the act of taking that box of books and placing it onto a designated, empty shelf (the mount point) within the library. Once mounted, those books (files) become seamlessly integrated and browsable as if they were always part of the library's structure.
Temporary vs. Persistent Mounts
-
Temporary Mounts with `mount` (Manual/On-Demand)
The
mountcommand allows you to manually attach a file system to a mount point. This mount is only temporary; it will be lost upon system reboot. This is ideal for removable media (USB drives), testing new configurations, or accessing data on a drive only occasionally.# 1. Create a mount point (if it doesn't exist) sudo mkdir /mnt/temp_usb # 2. Mount the device (e.g., /dev/sdb1) to the mount point sudo mount /dev/sdb1 /mnt/temp_usb # 3. Verify the mount df -hT /mnt/temp_usb lsblk | grep sdb1 # 4. Access files ls /mnt/temp_usb # 5. Unmount the device when done sudo umount /mnt/temp_usb # Or by device name: sudo umount /dev/sdb1Important: Unmounting
Always
umounta device before physically removing it or shutting down the system if it was mounted temporarily. Failure to do so can lead to data corruption. You cannot unmount a device if it is "busy" (e.g., a user is inside that directory or a process is accessing files on it). You might need to uselsof /mount/pointorfuser -m /mount/pointto identify and kill processes holding it open. -
Persistent Mounts with `/etc/fstab` (Automated/On-Boot)
For file systems that need to be available every time the system starts (e.g., root filesystem, data partitions, network shares), you must configure them in the
/etc/fstab(File System Table) file. This is the professional standard for server administration.
Critical Warning: Editing `/etc/fstab`
The /etc/fstab file is parsed by the system early in the boot sequence. A single syntax error or incorrect entry can render your system unbootable. Always follow these precautions:
- Backup First:
sudo cp /etc/fstab /etc/fstab.bak.$(date +%F) - Use UUIDs: Prefer using UUIDs (Universally Unique Identifiers) instead of device names (
/dev/sdb1). Device names can change if you add/remove disks, but a UUID is permanently associated with the file system itself, making mounts much more robust. - Test Immediately: After adding a new line, save the file and run
sudo mount -a. This command attempts to mount all file systems listed in/etc/fstabthat are not already mounted. If it runs without errors, your new entry is likely correct. - Double Check: Use
lsblkordf -hTto confirm the new mount point is correctly identified aftermount -a.
Deconstructing `/etc/fstab` Entries
Each line in /etc/fstab represents one file system to be mounted and contains six distinct fields, separated by whitespace (tabs or spaces).
| Column 1: Device Specifier | Column 2: Mount Point | Column 3: File System Type | Column 4: Mount Options | Column 5: Dump | Column 6: Pass |
|---|---|---|---|---|---|
UUID=a1b2c3d4-e5f6-...or /dev/sdb1or LABEL=MyDataDisk |
/data/var/log/mnt/backup |
xfsext4nfsswap |
defaultsnoatime,nodevroauto,noatime |
0 or 1 |
0 or 1 or 2 |
Identifies the device to mount.
|
The target directory. This must be an existing, empty directory on the main filesystem where the contents of the device will appear. | The type of the file system. Common types include xfs, ext4, nfs (for network shares), iso9660 (for CD-ROMs), swap (for swap partitions). |
Comma-separated list of mount options.
|
Used by the legacy dump backup utility.
|
Determines the order for fsck (filesystem check) at boot.
|
Example `/etc/fstab` entry:
UUID="a1b2c3d4-e5f6-7890-abcd-ef1234567890" /data xfs defaults,noatime 0 0This entry will mount the XFS file system with the specified UUID to the /data directory, using default options plus noatime, and it will not be dumped or checked at boot.
The Search Toolkit: `locate` vs. `find`
Once your file systems are mounted, you need efficient ways to navigate and locate specific files or directories. Linux provides two powerful commands for this, each optimized for different scenarios.
| `locate`: The Fast Index Search | `find`: The Powerful Real-Time Search |
|---|---|
How it Works: It does not search the live filesystem in real-time. Instead, it queries a pre-built database (/var/lib/mlocate/mlocate.db by default) that contains a list of all files and directories on the system. This database is typically updated once a day by a cron job. |
How it Works: It actively walks the filesystem tree from a specified starting point, examining every file and directory in real-time to see if it matches your search criteria. |
| Strength: Extremely fast. Results are almost instantaneous, regardless of the size of your filesystem, because it's just searching a flat file. | Strength: Infinitely flexible and always accurate. It searches the live filesystem, so it will find files created or deleted since the last database update. It can search by name, size, modification time, permissions, ownership, and more, and can execute actions on the found files. |
Weakness: The database can be out of date. It will not find files created, deleted, or renamed since the last updatedb run. It also typically doesn't search removable media unless explicitly configured. |
Weakness: Can be slow and resource-intensive, especially when searching large directory trees (like the entire / filesystem) or when complex criteria are used, as it has to read metadata for every item. |
| Best For: Quickly finding a file when you know all or part of its name, and you don't need real-time accuracy (e.g., finding system configuration files, documentation). | Best For: Complex, detailed, and real-time searches. Essential for scripting, system administration tasks, and when you need to perform actions on the search results. |
Deep Dive into `locate`
Before using locate for the first time, or if you suspect your database is out of date, you need to update it.
# Update the locate database (requires root privileges)
sudo updatedb
# Find files with "hosts" in their name anywhere on the system
locate hosts
# Find files ending with ".log"
locate .log
# Count how many files contain "conf" in their name
locate -c conf
# Find files that contain "nginx" in their path (not just filename)
locate nginxupdatedb scans your entire file system (excluding paths specified in /etc/updatedb.conf) and builds the database. This can take a few minutes on large systems.
locate is excellent for quick, broad searches where you just need to know *where* a file might be, assuming it's not brand new.
Mastering the `find` Command: The Administrator's Swiss Army Knife
find is arguably one of the most versatile and powerful command-line utilities. Its flexibility comes from its ability to combine search criteria with actions. The basic syntax is: find <where_to_look> <criteria> <action>
Let's break down common usage with comprehensive examples:
1. Specifying Where to Look (`<where_to_look>`)
This is the starting directory for the search. find will recursively search all subdirectories.
# Search current directory and its subdirectories
find .
# Search the entire root filesystem (can be slow!)
sudo find /
# Search a specific user's home directory
find /home/username2. Search Criteria (`<criteria>`)
This is where you define what you're looking for. You can combine multiple criteria.
- By Name (`-name`, `-iname`):
# Find all files ending in .conf anywhere under /etc (case-sensitive) find /etc -name "*.conf" # Find all files with "nginx" in their name (case-insensitive) find / -iname "*nginx*" # Find files named exactly "index.html" find /var/www -name "index.html"Wildcards like
*(any sequence of characters) and?(any single character) are expanded byfind, not the shell, so they should generally be quoted. - By Type (`-type`):
# Find all directories (d) inside the user's home find ~ -type d # Find all regular files (f) in the current directory find . -type f # Find symbolic links (l) in /var find /var -type l - By Modification Time (`-mtime`, `-mmin`):
# Find files modified exactly 7 days ago (full 24-hour periods) find /var/log -mtime 7 # Find files modified within the last 7 days (including today) find /var/www/html -mtime -7 # Find files modified more than 30 days ago find /tmp -mtime +30 # Find files modified within the last 60 minutes find /var/log -mmin -60-mtime N: Modified exactly N *24-hour periods* ago.-mtime +N: Modified more than N *24-hour periods* ago.-mtime -N: Modified less than N *24-hour periods* ago.-mminworks similarly but uses minutes. - By Size (`-size`):
# Find files larger than 10MB find /var/log -size +10M # Find files exactly 500KB find /home -size 500k # Find files smaller than 2 blocks (512-byte blocks) find /tmp -size -2c # 'c' for bytes, 'k' for KB, 'M' for MB, 'G' for GB - By Permissions (`-perm`):
# Find files with exactly 755 permissions (rwxr-xr-x) find . -perm 755 # Find files with at least 777 permissions (i.e., world-writable directories) find / -perm -777 -type d # The '-' means "at least these bits are set" # Find files where anyone can write (e.g., world-writable) find /var/www -perm /002 # The '/' means "any of these bits are set"-perm mode: Exact match for permissions.-perm -mode: Permissions include all of `mode`'s bits.-perm /mode: Permissions include any of `mode`'s bits. - By Owner/Group (`-user`, `-group`):
# Find all files owned by 'webadmin' find /var/www -user webadmin # Find all files belonging to the 'devs' group find /srv/projects -group devs - Combining Criteria (AND/OR):
By default, multiple criteria are combined with an implicit 'AND'. You can use
-ofor 'OR' and parentheses for grouping (remember to escape parentheses for the shell).# Find files modified in the last 7 days AND ending in .log find /var/log -type f -mtime -7 -name "*.log" # Find empty files OR empty directories in /tmp find /tmp \( -type f -empty -o -type d -empty \) # Find files owned by 'john' OR 'jane' find /home \( -user john -o -user jane \)
3. Actions (`<action>`)
This defines what find should do with the files that match your criteria. If no action is specified, the default action is -print (print the filename).
- Print (`-print`):
# Simply list the found files (default action) find /etc -name "*.conf" -print - Execute a Command (`-exec`): The Superpower!
This allows you to run any arbitrary command on each found file. The
{}acts as a placeholder for the current filename found byfind. The command must be terminated by\;(escaped semicolon) or+.# Find all files in /tmp older than 14 days and delete them # WARNING: Use with extreme caution! sudo find /tmp -type f -mtime +14 -exec rm {} \; # Find all shell scripts in a user's home and set them to be executable find ~ -name "*.sh" -exec chmod +x {} \; # Find all PDF files in /data and display their detailed listing find /data -name "*.pdf" -exec ls -l {} \; # Find all files larger than 100MB and list their size in human-readable format find /var/log -type f -size +100M -exec du -h {} \; # Find empty directories and remove them (using -delete for safety) find /path/to/search -type d -empty -delete # Or: find /path/to/search -type d -empty -exec rmdir {} +-exec command {} \;: Executes the command *once for each found file*. Good for commands that don't handle multiple arguments well (likerm).-exec command {} +: Executes the command *once for many found files*, passing them all as arguments to `command` (likexargs). More efficient for commands that can handle multiple arguments (likels,chmod,du). This is generally preferred for performance when possible.-delete: A specificfindaction to delete files or empty directories found. Safer than-exec rm {} \;as it has built-in checks and ensures only empty directories are removed when combined with-empty.
Comprehensive Lab: Adding and Managing a New Filesystem
Scenario: You've just physically added a brand new, unformatted disk (which the kernel has identified as /dev/sdb) to your server. Your mission is to prepare this disk for use by creating a partition, formatting it with the XFS filesystem, mounting it persistently at /data, and finally, practicing essential file management and discovery techniques using locate and find.
This lab walks you through the entire lifecycle of a new disk, from bare metal to integrated storage, emphasizing best practices and safety.
-
Identify the New Disk and Current Layout
Before making any changes, it's crucial to confirm which device is your new, unpartitioned disk. We'll use
lsblkfor this.$ lsblk -f NAME FSTYPE LABEL UUID MOUNTPOINT sda ├─sda1 xfs /boot a1b2c3d4-e5f6-7890-abcd-ef1234567890 /boot └─sda2 xfs / 0f0e0d0c-b9a8-7654-3210-fedcba987654 / sdb sr0 iso9660 CentOS 2023-01-01-12-34-56-00 /run/media/user/CentOSExpected Output: You should see a device like
sdblisted with noFSTYPE,LABEL,UUID, orMOUNTPOINTunder it. This confirms it's an unformatted, unpartitioned disk. If you don't see it, ensure the virtual disk is correctly added to your VM settings, or physically connected and recognized by the system. -
Create a Single Primary Partition on `/dev/sdb` using `fdisk`
We'll use
fdisk, a powerful command-line utility for managing disk partitions. We'll create one primary partition that uses the entire disk.sudo fdisk /dev/sdbYou'll enter an interactive prompt. Follow these steps carefully:
- Type
nand pressEnterto create a new partition. - Type
pand pressEnterto specify a primary partition. - Type
1and pressEnterfor partition number 1 (making it/dev/sdb1). - Press
Enterto accept the default first sector (start of the disk). - Press
Enteragain to accept the default last sector (end of the disk), using the entire disk for this partition. - Type
wand pressEnterto write the changes to the disk and exitfdisk.
Important: Refreshing the Partition Table
After modifying partitions with
fdisk, the kernel sometimes needs to be explicitly told to re-read the partition table. You might need to runsudo partprobeor, in some rare cases, reboot the system for/dev/sdb1to become fully visible. Verify its existence withlsblk -f.sudo partprobe lsblk -fNow,
lsblk -fshould show/dev/sdb1as a partition undersdb, still without a filesystem type or UUID. - Type
-
Create the XFS File System on the New Partition
With the partition created, we now lay down the filesystem structure. We'll use XFS, common for CentOS/RHEL systems, with
mkfs.xfs.sudo mkfs.xfs /dev/sdb1Command Explanation:
mkfs.xfsis the command to make a filesystem of type XFS./dev/sdb1is the target partition. This operation will format the partition, so be absolutely sure you're targeting the correct device!Expected Output: You'll see output indicating the creation of the XFS filesystem, including details about the superblock, data sections, and a generated UUID.
-
Create the Mount Point Directory
The mount point is just an empty directory where the contents of our new filesystem will appear. By convention, persistent data mounts are often placed under
/mntor directly under/, like/data.sudo mkdir /data sudo chmod 755 /data # Set sensible permissions for the mount pointPermissions:
chmod 755 /datameans the owner (root, in this case) has read, write, and execute permissions, while others have read and execute. This allows users to navigate into the directory but not necessarily write to it unless explicitly given permissions inside the mounted filesystem. -
Get the UUID of the New Partition's File System
Using the UUID for mounting is highly recommended because it provides a stable and unique identifier for your filesystem, preventing issues if device names change (e.g., if you add another drive and
/dev/sdb1becomes/dev/sdc1).sudo blkid /dev/sdb1 # Example output: /dev/sdb1: UUID="your-unique-uuid-string" TYPE="xfs"Action: Carefully copy the UUID string that is displayed. It will be a long alphanumeric string, for example:
e625a7a7-f4e2-4b2a-8c7e-1a2b3c4d5e6f. You'll use this in the next step. -
Make the Mount Persistent: Edit `/etc/fstab`
Now we instruct the system to automatically mount this new filesystem every time it boots. This is done by adding an entry to
/etc/fstab. Remember the CRITICAL WARNING about this file!sudo cp /etc/fstab /etc/fstab.bak.$(date +%F) # Backup first! sudo vim /etc/fstab # Use vim, nano, or your preferred text editorAdd a new line at the bottom of the file, replacing
"your-copied-uuid"with the actual UUID you copied in the previous step:UUID="e625a7a7-f4e2-4b2a-8c7e-1a2b3c4d5e6f" /data xfs defaults,noatime 0 0Line Breakdown:
UUID="...": Specifies the device by its unique ID./data: The mount point we created.xfs: The filesystem type.defaults,noatime: Mount options.defaultsincludes read-write, auto-mount, etc.noatimeimproves performance by preventing the system from updating file access times whenever a file is read.0: No dump (legacy backup tool).0: No filesystem check at boot (XFS handles this with its journaling).
Save and exit your text editor.
-
Test the `/etc/fstab` Entry and Verify the Mount
Before rebooting, always test your
fstabchanges!sudo mount -aCommand Explanation:
mount -aattempts to mount all filesystems listed in/etc/fstabthat are not already mounted. If there are any syntax errors in your new line, this command will fail and give you an error, allowing you to fix it before a reboot causes problems.Expected Output: If successful, there should be no output (or minimal output). If you get an error, carefully review step 6 and correct any typos.
Now, verify the mount using
lsblkanddf -hT:lsblk -f df -hT /dataVerification:
lsblk -fshould now show/dev/sdb1withFSTYPE="xfs"andMOUNTPOINT="/data".df -hT /datashould show the/dev/sdb1filesystem mounted, its size, and usage. -
Manage Files on the New Filesystem
Let's create some dummy files to simulate real data on our new mount point.
sudo touch /data/report_{1..5}.pdf sudo touch /data/archive.zip sudo mkdir /data/important_docs sudo touch /data/important_docs/memo.txt ls -l /dataThese commands create five PDF files and one ZIP file directly in
/data, and a directory with a text file inside it. You should see these files listed when you runls -l /data. -
Test `locate` for Quick File Discovery
We'll use
locateto find one of the newly created files. Remember thatlocateuses a database, so we need to update it first.sudo updatedb # Update the database to include our new files locate report_3.pdf locate archive.zip locate memo.txtExpected Output: All three
locatecommands should instantly return the full path to the files (e.g.,/data/report_3.pdf). This demonstrates the speed oflocateonce its database is up-to-date. -
Test `find` for Complex Search and Actions
Now, let's use the more powerful
findcommand to perform a targeted search and an action on the results.# Find all PDF files on the /data mount and display their detailed listing sudo find /data -name "*.pdf" -exec ls -l {} \; # Find all files created in /data in the last 10 minutes and list them sudo find /data -mmin -10 -type f # Find all empty directories within /data and delete them sudo find /data -type d -empty -deleteExample 1: This command searches within
/datafor any file ending in.pdfand, for each match, executesls -lto show its details. You should see the five report PDFs listed.Example 2: This finds any regular files within
/datathat have been modified in the last 10 minutes (useful for seeing recently created files). You should see your report PDFs, archive.zip, and memo.txt if you ran the creation commands recently.Example 3: This command is very powerful. It looks for any empty directories within
/dataand safely deletes them. If you created any empty directories as part of your testing, this would remove them. (Theimportant_docsdirectory is not empty, so it won't be deleted).
Congratulations! You have successfully added a new physical disk to your Linux system, configured its partitioning and filesystem, set up persistent mounting, and demonstrated your ability to find and manage files on it using essential command-line tools. These are fundamental skills for any Linux administrator.