Linux Filesystem Hierarchy Explained – Master Your System Structure

Linux Filesystem Hierarchy

Photo by Pankaj Patel on Unsplash

TL;DR
In a typical Linux system the directory tree is not arbitrary; it follows the Filesystem Hierarchy Standard (FHS). Understanding where configuration files, user data, logs, and optional packages live lets you keep your system tidy, troubleshoot faster, and write reproducible automation scripts.


Why the Hierarchy Matters Today

Modern Linux distributions ship hundreds of thousands of files – from core libraries in /lib to per‑user data in /home. When a server runs for years or a workstation is shared among many users, confusion about where to put a file can lead to:

  • Security gaps (configuring a service in the wrong directory may expose it to unintended users).
  • Backup failures (missing critical directories because you didn’t know they exist).
  • Upgrade headaches (system upgrades that overwrite files placed outside their intended location).

A solid grasp of the hierarchy turns the filesystem from a chaotic forest into an organized garden where every plant knows its spot. In this article we’ll walk through the key top‑level directories, give practical examples of navigation and management, and share best practices for keeping your Linux system clean and predictable.


1. The Core of the Hierarchy: /etc – System Configuration

Path Typical Content Why It Matters
/etc/hosts Static host‑name mapping Prevents DNS lookups, useful for local testing
/etc/passwd, /etc/shadow User accounts & passwords Core of the login system
/etc/fstab Filesystem mount table Controls what gets mounted at boot
/etc/ssh/sshd_config SSH daemon config Security‑critical setting for remote access

Practical Tips

  • Keep it version‑controlled: Many sysadmins store /etc in a Git repo (e.g., with git init /etc && git add .) to track changes. Never commit secrets like /etc/shadow.
  • Use the update-alternatives tool for packages that provide multiple versions of a binary, e.g., choosing between Java 8 and 11.
  • Automate backups: A simple cron job can snapshot /etc every night (rsync -a /etc /backup/etc/$(date +%F)).

Common Pitfall

Editing system files without sudo
Running a text editor directly on /etc/passwd as a normal user will fail. Always prepend with sudo, or use tools that respect file permissions (e.g., sudo nano /etc/ssh/sshd_config).


2. Variable Data: /var

Path Typical Content Why It Matters
/var/log System logs (syslog, kern.log) Essential for debugging failures
/var/cache Package caches, web server cache Freeing space by cleaning can improve performance
/var/lib State information (e.g., package databases) Persistent data that should survive upgrades
/var/spool Print jobs, mail queues Queued tasks awaiting processing

Practical Tips

  • Rotating logs: Configure logrotate to keep only the last 7 days of logs (/etc/logrotate.d/syslog).
  • Cleaning package cache (Debian/Ubuntu): sudo apt clean. For RPM‑based systems, use yum clean all.
  • Monitoring disk usage: du -sh /var/* | sort -h quickly shows which subdirectory consumes the most space.

Common Pitfall

Deleting /var/lib contents blindly
Removing files from /var/lib/apt/lists or similar will break package management. Always understand what a file stores before deleting it.


3. Optional Packages: /opt

The /opt directory is reserved for third‑party applications that don’t integrate with the standard packaging system. Think of large suites like Google Chrome, MATLAB, or proprietary software bundled as tarballs.

Path Typical Content Why It Matters
/opt/google/chrome Google Chrome installation Keeps it isolated from core packages
/opt/microsoft/msodbcsql17 Microsoft ODBC driver Avoids clashes with system libraries

Practical Tips

  • Create a wrapper script: For software that doesn’t expose a PATH entry, add /opt/<app>/bin to your $PATH in .profile.
  • Use symlinks for convenience: ln -s /opt/google/chrome/google-chrome ~/chrome.
  • Keep version numbers in directory names (/opt/appname/v1.2) so you can roll back easily.

Common Pitfall

Running executables directly from /opt without a wrapper
This may break if the application expects its resources relative to its install dir. Always use the official launch script or symlink.


4. User Space: /home

Path Typical Content Why It Matters
/home/username/.config Application settings (e.g., VS Code) Keeps per‑user config separate from system defaults
/home/username/Documents Personal files Default workspace for users
/home/username/.cache Cached data (e.g., thumbnails) Can be cleared to free space

Practical Tips

  • Use rsync or unison for cross‑machine backups of home directories.
  • Hide dotfiles: In file managers, enable “show hidden files” (Ctrl+H) to see config directories.
  • Set proper ownership: After restoring from backup, ensure each user’s files are owned by them (chown -R username:username /home/username).

Common Pitfall

Mounting external storage on /home
If you mount a USB drive over /home, you’ll lose access to your personal data. Instead, use a subdirectory like /mnt/usb.


5. Runtime Files and Temporary Data: /tmp & /run

Path Typical Content Why It Matters
/tmp Temporary files created by applications Cleared on reboot or manually
/run Runtime data (e.g., PID files, sockets) Stores information that must persist only while the system is booted

Practical Tips

  • Secure temporary directories: Set TMPDIR=/var/tmp for long‑lived temp files.
  • Clean /tmp: Add a cron job (find /tmp -type f -mtime +7 -delete) to remove stale files.

Common Pitfall

Relying on /tmp for persistent data
Data in /tmp disappears after reboot; never store critical config here.


6. System Boot and Kernel: /boot

Path Typical Content Why It Matters
/boot/vmlinuz-* Linux kernel binaries The core of the boot process
/boot/initrd.img-* Initial RAM disk images Provides drivers needed during early boot
/boot/grub.cfg GRUB configuration Determines which kernel to load

Practical Tips

  • Keep old kernels: Most distros keep a few previous kernels for fallback. Remove them cautiously (sudo apt remove linux-image-5.4.0-42-generic).
  • Update grub after kernel changes: Run sudo update-grub.

Common Pitfall

Modifying /boot/grub.cfg directly
GRUB regenerates this file on boot; manual edits are overwritten.


7. Package Management Directories

Path Typical Content Why It Matters
/var/cache/apt/archives Debian package caches Freeing space can be done safely (sudo apt clean)
/var/lib/dpkg/info Debian package metadata Essential for dpkg --configure -a

Practical Tips

  • Audit installed packages: dpkg-query -l | grep '^rc' shows packages removed but still have config files.
  • Clean orphaned dependencies: sudo apt autoremove.

8. Managing the Hierarchy with Bash – A Hands‑On Walkthrough

Below is a short script that backs up critical directories, cleans cache, and reports disk usage:

#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="/backup/$(date +%F)"
mkdir -p "$BACKUP_DIR"

# 1. Backup /etc
rsync -a --delete /etc/ "$BACKUP_DIR/etc"

# 2. Clean package cache
sudo apt clean

# 3. Report disk usage
echo "Disk usage summary:"
du -shx /* | sort -h | head -20

Run it with bash backup_and_clean.sh. Adjust paths for RPM‑based systems (yum clean all).


9. Common Misconceptions & How to Avoid Them

Myth Reality
“All config files live in /etc.” Many applications store per‑user configs in ~/.config; system daemons may keep state in /var/lib.
“Delete everything under /tmp to free space.” Some programs need /tmp for runtime; only delete stale files (find /tmp -type f -mtime +7).
“You can put any file anywhere as long as you know the path.” Permissions, ownership, and directory semantics matter. For example, putting a log file in /etc will cause permission errors if not owned by root.

10. Best Practices Checklist

  • Always check documentation before moving files into system directories.
  • Use package managers for installing software; only resort to /opt for truly un-packaged applications.
  • Version‑control critical config (/etc) but exclude secrets.
  • Automate backups of /etc, /var/log, and user data.
  • Regularly clean caches (apt clean, yum clean all).
  • Monitor disk usage with tools like ncdu or du.

Conclusion

The Linux filesystem hierarchy is a well‑thought‑out blueprint that keeps systems predictable, secure, and maintainable. By knowing where to find configuration files in /etc, where variable data lives in /var, how optional packages should be isolated under /opt, and how user data is kept in /home, you can:

  • Troubleshoot faster (quickly locate logs or config changes).
  • Automate reliably (write scripts that work across distributions).
  • Keep systems clean (regular housekeeping without breaking anything).

Treat the hierarchy not as a rigid rule set but as a contract between your system and you. Respect it, and your Linux experience will be smoother, safer, and more efficient.


Frequently Asked Questions (FAQ)

What is the purpose of the /etc directory in Linux?

/etc stores all system‑wide configuration files such as user accounts, network settings, and service configurations. Keeping these files in one place allows administrators to manage system behavior consistently across reboots and upgrades.

Why should I avoid deleting files from /var/lib?

Files under /var/lib contain persistent state data for packages, databases, and services (e.g., apt cache, package metadata). Removing them can break package management or corrupt application state, leading to failures that are hard to diagnose.

Where should third‑party applications that aren’t packaged by the distribution be installed?

Third‑party software that doesn’t use the system’s packaging manager should reside in /opt. This keeps it isolated from core system files and simplifies cleanup or upgrades of those standalone packages.

How can I safely back up my configuration files in /etc?

Create a versioned backup using rsync, tar, or a Git repository:

sudo rsync -a /etc /backup/etc/$(date +%F)

Exclude sensitive files like /etc/shadow and use file‑permission checks to avoid accidental exposure.

Related Articles

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Scroll to Top