Skip to content

📂 The Linux File System

"Everything in Linux is a file - even the hardware."


📑 Table of Contents


🗂️ What is a File System?

  • A file system controls how data is stored and retrieved
  • Each group of data is called a file, and the structure and logic rules used to manage files and their names are called file systems
  • A file system is a logical collection of files on a partition or disk
  • On a Linux system, everything is considered to be a file
  • On Linux, file and directory names are case-sensitive

Types of "Files" in Linux

Since everything is a file, Linux treats many things as files:

TypeExamples
Regular filesText files, images, binaries
DirectoriesFolders containing other files
Device files/dev/sda (disk), /dev/null
Symbolic linksShortcuts to other files
Sockets & pipesInter-process communication

Common Linux File Systems

File SystemDescription
ext4Default for most Linux distros, reliable and mature
xfsHigh-performance, good for large files (RHEL default)
btrfsModern with snapshots and compression support
ntfsWindows file system (read/write support in Linux)
vfat/fat32USB drives, cross-platform compatibility

Key Characteristics

  • No drive letters — everything is mounted under a single root (/)
  • Hidden files start with a dot (.bashrc, .config/)
  • Extensions are optional — Linux identifies files by content, not extension
  • Path separator is forward slash (/), not backslash
bash
# Check what file system a partition uses
df -Th

# Identify a file's actual type (regardless of extension)
file myfile.txt

🌳 The Filesystem Hierarchy Standard

Linux follows the Filesystem Hierarchy Standard (FHS), organizing all files under a single root (/).

DirectoryDescription
/binBinaries or user executable files available to all users
/sbinSystem binaries that only the superuser will need
/bootFiles required for starting your system
/homeUser home directories (all users except root)
/devDevice files
/etcSystem-wide configuration files
/libShared library files used by different applications
/mediaMount point for external storage (automatically mounted)
/mntManual mount point (less commonly used these days)
/tmpTemporary files saved by running applications. Non-privileged users may also store files here temporarily
/procVirtual directory with hardware info (CPU, RAM, Kernel). Generated at boot or on-the-fly as the system runs
/sysInformation about devices, drivers, and some kernel features
/srvData for servers
/runTemporary file system which runs in RAM
/usrUser binaries, shared libraries, and more. On some distros (like CentOS), many commands are in /usr/bin and /usr/sbin instead of /bin and /sbin
/varVariable-length files such as logs (files that register events on the system)
/
├── bin/       → Essential user binaries
├── sbin/      → System binaries
├── boot/      → Boot loader files
├── home/      → User home directories
├── dev/       → Device files
├── etc/       → Configuration files
├── lib/       → Shared libraries
├── media/     → Removable media (auto-mount)
├── mnt/       → Manual mount point
├── tmp/       → Temporary files
├── proc/      → Process & hardware info (virtual)
├── sys/       → Device & kernel info (virtual)
├── srv/       → Server data
├── run/       → Runtime data (RAM)
├── usr/       → User programs & libraries
└── var/       → Variable data (logs, caches)

🚶 Walking Through the File System

Essential Navigation Commands

CommandDescription
pwdPrint working directory — shows your current location
cdChange directory — move to a different location
lsList contents of a directory
treeVisual representation of directory structure

Path Shortcuts

SymbolMeaning
~Current user's home directory
/Root of the file system
.Current directory
..Parent directory
-Previous directory

Examples

bash
# Where am I?
pwd
# /home/v43

# Go to home directory
cd ~
cd          # Same as cd ~

# Go to root
cd /

# Go up one directory
cd ..

# Go to previous directory
cd -

# List files
ls
ls -la      # Long format with hidden files

# View directory tree
tree
tree -L 2   # Limit depth to 2 levels

📋 The ls Command

The ls command lists directory contents. Combine flags for more detailed output.

Common Flags

FlagDescription
-lLong list format (permissions, owner, size, date)
-aShow all files (including hidden files starting with .)
-SSort by size (descending)
-hHuman-readable sizes (KB, MB, GB)
-xSort by extension

Examples

bash
# Basic listing
ls

# Long format
ls -l

# Show hidden files
ls -a

# Combine flags: long format, all files, human-readable sizes
ls -lah

# Sort by size (largest first)
ls -lSh

# Sort by extension
ls -lx

Reading ls -l Output

-rw-r--r-- 1 user group 4096 Jan 20 10:00 file.txt
│└──┬───┘  │  │    │     │       │         └── Filename
│   │      │  │    │     │       └── Modification date
│   │      │  │    │     └── File size
│   │      │  │    └── Group owner
│   │      │  └── User owner
│   │      └── Number of hard links
│   └── Permissions (owner/group/others)
└── File type (- = file, d = directory, l = link)

🕐 File Timestamps

Every file in Linux has three timestamps that track different events.

TimestampNameDescriptionView with
atimeAccess timeLast time the file was readls -lu
mtimeModification timeLast time the file contents were modifiedls -l, ls -lt
ctimeChange timeLast time file metadata was changed (permissions, owner, etc.)ls -lc

Viewing Timestamps

bash
# Show modification time (default)
ls -l

# Sort by modification time (newest first)
ls -lt

# Show access time
ls -lu

# Show change time (metadata)
ls -lc

# Show all timestamps with stat
stat file.txt

Example stat Output

bash
$ stat file.txt
  File: file.txt
  Size: 4096       Blocks: 8          IO Block: 4096   regular file
Access: 2024-01-20 10:30:00.000000000 +0000
Modify: 2024-01-19 15:45:00.000000000 +0000
Change: 2024-01-19 15:45:00.000000000 +0000
 Birth: -

💡 Note: Reading a file updates atime, editing content updates mtime, and changing permissions/ownership updates ctime. Many systems use relatime/noatime, so atime may not update on every read.


👁️ Viewing Files

cat — Concatenate and Display

Displays file contents in the terminal. Best for smaller files.

bash
cat file.txt              # Display file contents
cat -n file.txt           # Show line numbers
cat file1.txt file2.txt   # Display multiple files together

less — Interactive Pager

Better for viewing long files with navigation and search capabilities.

bash
less file.txt
KeyAction
hShow help
Space / fForward one page
bBack one page
/patternSearch forward
?patternSearch backward
nNext search result
NPrevious search result
gGo to beginning
GGo to end
qQuit

head — View Beginning of File

Shows the first 10 lines of a file by default.

bash
head file.txt             # First 10 lines
head -n 20 file.txt       # First 20 lines

tail — View End of File

Shows the last 10 lines of a file by default.

bash
tail file.txt             # Last 10 lines
tail -n 20 file.txt       # Last 20 lines
tail -f file.txt          # Follow file in real-time (great for logs)

watch — Monitor Command Output

Runs a command repeatedly (every 2 seconds by default) and displays the output.

bash
watch ls                  # Watch folder for changes
watch -n 1 ls             # Update every 1 second
watch "df -h"             # Monitor disk space

🛠️ Handling Files

Creating Files and Directories

CommandDescription
touch file.txtCreate an empty file (or update timestamp)
mkdir dirCreate a directory
mkdir dir1 dir2Create multiple directories
mkdir -p parent/childCreate nested directories
bash
touch newfile.txt
mkdir projects
mkdir -p projects/web/src

Copying Files — cp

bash
cp file1.txt file2.txt              # Copy file1 to file2 (overwrites)
cp file1.txt file2.txt dir/         # Copy multiple files to directory
cp -r dir1/ dir2/                   # Copy directory recursively
cp -p file1.txt file2.txt           # Preserve permissions and ownership

💡 Note: By default, the user who copies becomes the owner of the new file. Use -p to preserve original permissions.

Moving and Renaming — mv

bash
mv file.txt /new/location/          # Move file to new location
mv oldname.txt newname.txt          # Rename file
mv file1.txt file2.txt dir/         # Move multiple files to directory
mv *.txt documents/                 # Move all .txt files to directory

⚠️ Warning: mv overwrites files without warning if they already exist at the destination.

Removing Files and Directories — rm

bash
rm file.txt                         # Remove file
rm file1.txt file2.txt              # Remove multiple files
rm -r directory/                    # Remove directory and contents
rm -f file.txt                      # Force remove (no confirmation)
rm -rf directory/                   # Force remove directory (use with caution!)

⚠️ Safety Tips:

  • Always use tab-autocomplete when removing files to avoid typos
  • rm removes directory entries; data is freed when the last link is removed (but may still be recoverable)
  • Use shred for secure deletion of sensitive files

Secure Deletion — shred

bash
shred -u file.txt                   # Overwrite and remove file securely
shred -n 5 file.txt                 # Overwrite 5 times (default is 3)

⚠️ Note: shred is unreliable on SSDs and copy-on-write filesystems (btrfs/zfs). Prefer full-disk encryption and device secure-erase when possible.

Quick Reference

TaskCommand
Create filetouch file.txt
Create directorymkdir dir
Copy filecp src dest
Copy directorycp -r src/ dest/
Move/renamemv src dest
Remove filerm file
Remove directoryrm -r dir/
Secure deleteshred -u file

Links allow you to reference files from multiple locations without duplicating data.

  • Points directly to the file's data (inode) on disk
  • Cannot link to directories
  • Cannot cross filesystem boundaries
  • File data remains until all hard links are deleted
  • Same inode number as the original
bash
ln original.txt hardlink.txt
ls -li    # Shows same inode number for both
  • Points to the file's path (like a shortcut)
  • Can link to directories
  • Can cross filesystem boundaries
  • Breaks if the target is moved or deleted
bash
ln -s /path/to/original symlink.txt
ls -l symlink.txt
# symlink.txt -> /path/to/original

Comparison

FeatureHard LinkSymbolic Link
Links toInode (data)Path (name)
Cross filesystemNoYes
Link to directoryNoYes
Original deletedData preservedLink breaks
Commandln file linkln -s file link
bash
# Create hard link
ln original.txt hardlink.txt

# Create symbolic link
ln -s /path/to/original symlink.txt

# Find what a symlink points to
readlink symlink.txt

# Find all hard links to a file (by inode)
find / -inum $(stat -c %i original.txt) 2>/dev/null

⚖️ Comparing Files

cmp — Byte-by-Byte Comparison

Check if two files are identical. Works with both text and binary files.

bash
cmp file_a file_b
# No output = files are identical
# Shows first difference location if different

sha256sum — Checksum Comparison

Generate a cryptographic hash of a file. Even a single bit difference results in a completely different checksum.

bash
sha256sum file_a
sha256sum file_b

# Compare checksums directly
sha256sum file_a file_b

diff — Line-by-Line Comparison

Shows the specific lines that differ between files. Essential for development work and comparing commits.

bash
diff file_a file_b
FlagDescription
-BIgnore blank lines
-wIgnore whitespace
-cContext format (more verbose)
-uUnified format (commonly used for patches)
-ySide-by-side comparison
bash
diff -B file_a file_b       # Ignore blank lines
diff -w file_a file_b       # Ignore whitespace
diff -c file_a file_b       # Verbose context format
diff -u file_a file_b       # Unified format (for patches)

💡 Tip: diff output is used by the patch program to apply fixes. See man patch for more details.


🗜️ Compressing and Archiving Files

tar is an archiver: it combines files/folders into one archive.
Compression is optional and added using flags like -z, -j, or -J.

Common tar Flags

FlagMeaning
-cCreate archive
-xExtract archive
-tList archive contents
-fArchive filename
-vVerbose output
-zUse gzip compression
-jUse bzip2 compression
-JUse xz compression
-CExtract into target directory
--exclude='PATTERN'Exclude matching files

Creating Archives

bash
tar -cvf backup.tar project/                     # Archive only (no compression)
tar -czvf backup.tar.gz project/                 # gzip compression
tar -cjvf backup.tar.bz2 project/                # bzip2 compression
tar -cJvf backup.tar.xz project/                 # xz compression
tar -czvf logs.tar.gz app.log nginx.log configs/ # Multiple sources

Listing and Extracting

bash
tar -tvf backup.tar.gz                           # List contents
tar -xvf backup.tar                              # Extract .tar
tar -xzvf backup.tar.gz                          # Extract .tar.gz
tar -xjvf backup.tar.bz2                         # Extract .tar.bz2
tar -xJvf backup.tar.xz                          # Extract .tar.xz
tar -xzvf backup.tar.gz -C /tmp/restore/         # Extract to directory

Excluding Files

bash
tar --exclude='*.mkv' --exclude='node_modules' -czvf project.tar.gz project/

File Naming Conventions

ExtensionMeaning
.tarArchive only (no compression)
.tar.gz / .tgztar + gzip
.tar.bz2tar + bzip2
.tar.xztar + xz

Single-File Compression Tools

Use these when you want to compress one file without creating a .tar archive:

bash
gzip file.txt         # Creates file.txt.gz
gunzip file.txt.gz    # Decompress
gzip -k file.txt      # Keep original file

bzip2 file.txt        # Creates file.txt.bz2
bunzip2 file.txt.bz2

xz file.txt           # Creates file.txt.xz
unxz file.txt.xz

📚 Quick Reference Card

bash
pwd                     # Print working directory
cd /path/to/dir         # Change directory
cd ~                    # Go to home directory
cd -                    # Go to previous directory
ls -la                  # List all files with details
tree -L 2               # Directory tree (2 levels deep)

Viewing Files

bash
cat file.txt            # Display entire file
cat -n file.txt         # Display with line numbers
less file.txt           # Interactive pager
head -n 20 file.txt     # First 20 lines
tail -n 20 file.txt     # Last 20 lines
tail -f file.txt        # Follow file in real-time

File Operations

bash
touch file.txt          # Create empty file
mkdir -p dir/subdir     # Create nested directories
cp -r src/ dest/        # Copy directory recursively
cp -p file1 file2       # Copy preserving permissions
mv old.txt new.txt      # Rename file
mv file.txt dir/        # Move file to directory
rm file.txt             # Remove file
rm -r directory/        # Remove directory

Compression & Archiving

bash
tar -cvf archive.tar dir/                         # Create tar archive
tar -czvf archive.tar.gz dir/                     # Create gzip-compressed archive
tar -cjvf archive.tar.bz2 dir/                    # Create bzip2-compressed archive
tar -cJvf archive.tar.xz dir/                     # Create xz-compressed archive
tar -tvf archive.tar.gz                           # List archive contents
tar -xzvf archive.tar.gz -C /path/to/extract/     # Extract into target directory
tar --exclude='*.log' -czvf archive.tar.gz dir/   # Exclude matching files
gzip -k file.txt                                  # Compress single file and keep original
gunzip file.txt.gz                                # Decompress single file
bash
ln file hardlink        # Create hard link
ln -s file symlink      # Create symbolic link
readlink symlink        # Show link target

File Information

bash
file myfile             # Identify file type
stat myfile             # Detailed file info
ls -li                  # Show inode numbers
df -Th                  # Disk space by filesystem
du -sh directory/       # Directory size

Timestamps

bash
ls -l                   # Show modification time
ls -lu                  # Show access time
ls -lc                  # Show change time
ls -lt                  # Sort by modification time
stat file.txt           # Show all timestamps

📝 Note: This guide covers standard Linux file system operations. Some commands may vary slightly between distributions. When in doubt, use man <command> for detailed documentation.

Released under the MIT License.