Navigating the Filesystem
Navigating the Filesystem
Everything in Linux is organized in a hierarchical tree-like filesystem. Before you can do anything usefulβedit files, run programs, analyze logsβyou need to know how to navigate this structure. Think of the filesystem as a building: directories (folders) are rooms, files are objects in those rooms, and paths are the directions to get there.
Why filesystem navigation matters:
- Foundation of everything: Every command operates on files and directories
- Context awareness: Understanding where you are prevents accidental file operations in the wrong location
- Efficiency: Mastering navigation shortcuts saves hours of typing
- Remote work: When SSH'd into a server, the GUI doesn't existβnavigation is everything
This tutorial teaches you the essential commands (pwd, cd, ls) and concepts (absolute vs relative paths, wildcards) that form the foundation of working with any Unix-like system.
The Linux Directory Structure
Linux follows the Filesystem Hierarchy Standard (FHS), a standard directory layout used by virtually all Unix-like systems. Understanding this structure helps you know where to find things and where to put things.
/ β Root (the top-level directoryβeverything starts here)
βββ bin/ β Essential user binaries (ls, cp, mv, bash)
βββ boot/ β Boot loader files (kernel, initrd)
βββ dev/ β Device files (hard drives, USB, terminals)
βββ etc/ β System configuration files
βββ home/ β User home directories
β βββ alice/ β Alice's personal files
β βββ bob/ β Bob's personal files
βββ lib/ β Shared libraries (like Windows DLLs)
βββ media/ β Mount points for removable media (USB drives, CDs)
βββ mnt/ β Mount points for temporary filesystems
βββ opt/ β Optional/third-party software
βββ proc/ β Virtual filesystem for process info (not real files!)
βββ root/ β Root user's home directory (not /home/root!)
βββ sbin/ β System administration binaries (requires root)
βββ srv/ β Service data (web servers, FTP)
βββ sys/ β Virtual filesystem for system/hardware info
βββ tmp/ β Temporary files (cleared on reboot)
βββ usr/ β User programs and data (read-only)
β βββ bin/ β User binaries (most commands you use)
β βββ lib/ β Libraries for /usr/bin programs
β βββ local/ β Locally installed software (not from packages)
β βββ share/ β Shared data (docs, icons, man pages)
βββ var/ β Variable data (changes during operation)
βββ log/ β Log files (application and system logs)
βββ tmp/ β Temporary files (preserved across reboots)
βββ www/ β Web server files (on many systems)
Key Directory Purposes
| Directory | Purpose | Examples |
|---|---|---|
/bin | Essential commands needed in single-user mode | ls, cp, cat, bash |
/etc | System configuration files | nginx.conf, passwd, fstab |
/home | User home directories | /home/alice, /home/bob |
/tmp | Temporary files (anyone can write) | Session data, temp downloads |
/usr/bin | Most user commands | python, git, vim, wget |
/var/log | Log files | syslog, auth.log, nginx/access.log |
/opt | Third-party applications | /opt/google/chrome |
/dev | Device files | /dev/sda1 (hard drive), /dev/null |
βΉοΈ Everything is a file
In Linux, virtually everything is represented as a fileβregular files, directories, hardware devices (/dev/sda1), processes (/proc/1234), and even network connections. This "everything is a file" philosophy is one of Unix/Linux's most powerful design decisions, enabling uniform access patterns across different resources.
Why this matters: When you see a command like sudo nano /etc/nginx/nginx.conf, you immediately know:
/etc= system configurationnginx/= nginx-specific config- Requires
sudobecause system configs aren't user-writable
Absolute vs Relative Paths
Understanding paths is absolutely fundamental. Every file and directory has a pathβthe "address" of where it lives.
Absolute Paths
An absolute path always starts from the root directory (/) and specifies the complete location.
/home/alice/Documents/report.txt
/etc/nginx/nginx.conf
/var/log/syslog
/usr/bin/python3Characteristics:
- Always starts with
/ - Works from anywhere (context-independent)
- Unambiguousβonly one meaning
- Longer to type
When to use absolute paths:
- Scripts (so they work regardless of where you run them)
- Referring to system files (
/etc,/var/log) - When you need certainty about the exact location
Relative Paths
A relative path starts from your current directory and doesn't begin with /.
# If you're in /home/alice:
Documents/report.txt # Same as /home/alice/Documents/report.txt
../bob/file.txt # Go up to /home, then into bob/
../../etc/hostname # Go up twice to /, then into etc/Characteristics:
- Does NOT start with
/ - Depends on current directory (context-dependent)
- Shorter to type
- Can break if you're not where you think you are
When to use relative paths:
- Interactive work (faster typing)
- Within a project directory structure
- Temporary navigation
Special Path Symbols
These special symbols save massive amounts of typing:
| Symbol | Meaning | Example | Result |
|---|---|---|---|
/ | Root directory | cd / | Go to root |
~ | Your home directory | cd ~/Documents | Go to your Documents folder |
. | Current directory | ./script.sh | Run script in current directory |
.. | Parent directory (one level up) | cd .. | Go up one level |
- | Previous directory | cd - | Toggle to last location |
~user | Another user's home | cd ~bob | Go to bob's home (if allowed) |
Example workflow:
pwd # /home/alice
cd /var/log # Absolute path to logs
pwd # /var/log
cd ~/Projects # ~ expands to /home/alice
pwd # /home/alice/Projects
cd .. # Go up one level
pwd # /home/alice
cd - # Go back to previous directory
pwd # /home/alice/Projectsπ‘ The tilde (~) is your friend
~ always expands to your home directory, no matter where you are. This makes commands portable:
cd ~always takes you homecp file.txt ~/backup/always copies to your backup folder~/.bashrcalways refers to your personal config
Much better than typing /home/alice every time!
pwd β Where Am I?
The pwd command (Print Working Directory) shows your current location in the filesystem. This is your "GPS coordinates" in the terminal.
pwd
# Output: /home/alice
# After navigating somewhere
cd /var/log
pwd
# Output: /var/log
# The environment variable $PWD also contains this info
echo $PWD
# Output: /var/logWhy you need pwd:
- Orientation: When you open a terminal, you might not know where you are
- Confirmation: Before running dangerous commands (
rm,mv), verify your location - Scripting: Capture the current directory to return to later
- Debugging: When commands fail, check if you're in the right place
# Common pattern: save location, do work elsewhere, return
original_dir=$(pwd)
cd /tmp
# ... do some work ...
cd "$original_dir" # Return to where you startedIf you ever feel lost in the terminal, pwd is your GPS. Use it frequently when learning! Combine with ls to see what's around you: pwd; ls
cd β Moving Around
The cd command (Change Directory) is how you move through the filesystem. It's the most frequently used command you'll type.
Basic cd Usage
# Go to your home directory (all of these are equivalent)
cd
cd ~
cd $HOME
# Go to an absolute path
cd /var/log # System logs
cd /etc/nginx # Nginx configuration
cd /home/alice/Documents # Specific directory
# Go to a relative path (from current location)
cd Documents # Move into Documents subdirectory
cd Documents/Projects # Move into nested directory
cd Projects/my-app/src # Multiple levels at once
# Go up one level (to parent directory)
cd ..
# Go up two levels
cd ../..
# Go up and into a sibling directory
cd ../other-directory
# Go to the previous directory (toggle between two locations)
cd -
# Go to another user's home (if you have permission)
cd ~bobAdvanced cd Patterns
# Start in home directory
cd ~
pwd # /home/alice
# Navigate to a deeply nested project
cd Documents/Projects/web-app/frontend/src/components
pwd # /home/alice/Documents/Projects/web-app/frontend/src/components
# Quick jump to parent directory
cd ..
pwd # /home/alice/Documents/Projects/web-app/frontend/src
# Jump multiple levels up
cd ../../..
pwd # /home/alice/Documents/Projects
# Toggle between two directories (very useful!)
cd /var/log
pwd # /var/log
cd /etc/nginx
pwd # /etc/nginx
cd - # Back to /var/log
pwd # /var/log
cd - # Back to /etc/nginx
pwd # /etc/nginx
# Go to root, then home
cd /
pwd # /
cd
pwd # /home/aliceTab Completion: Your Superpower
Tab completion is the single most important keyboard shortcut for navigation. It:
- Saves typing
- Prevents typos
- Shows you what's available
- Works with commands, files, directories, and variables
How it works:
- Type the first few letters of a directory name
- Press
Tab - If there's one match, it auto-completes
- If there are multiple matches, press
Tabtwice to see all options
# Example: navigating to /etc/nginx/
cd /etc/ng<Tab> # Completes to: cd /etc/nginx/
cd /etc/nginx/conf<Tab> # Completes to: cd /etc/nginx/conf.d/
# Multiple matches: press Tab twice to see options
cd /etc/n<Tab><Tab>
# Shows: netconfig network/ NetworkManager/ nginx/
# You can then type more characters and Tab again
cd /etc/ng<Tab> # Now completes uniquely to nginx/π‘ Use Tab completion religiously!
Never type full directory names manually. Always use Tab completion. It's faster, prevents errors, and shows you what exists. This habit alone will make you 10x faster in the terminal.
Common cd Mistakes and Solutions
Problem: cd to a directory with spaces
# Wrong (interprets as two arguments)
cd My Documents # Error: bash: cd: My: No such file or directory
# Right (quote the path)
cd "My Documents"
cd 'My Documents'
cd My\ Documents # Escape the spaceProblem: Permission denied
cd /root # Error: Permission denied (unless you're root)
sudo cd /root # Still doesn't work (cd is a shell builtin)
# Solution: Use sudo -i or su to become root first
sudo -i # Become root
cd /root # Now worksls β Listing Contents
The ls command (List) shows the contents of a directory. It's how you see what files and directories exist.
Basic ls Usage
# List files in current directory
ls
# List files in a specific directory
ls /etc
# List with details (long format)
ls -l
# List all files (including hidden files starting with .)
ls -a
# Combine options: long format + all files
ls -la
# Human-readable file sizes (KB, MB, GB)
ls -lhUnderstanding ls -l Output
The long format (ls -l) shows detailed information about each file:
ls -lOutput:
-rw-r--r-- 1 alice staff 4096 Jan 15 10:30 document.txt
drwxr-xr-x 3 alice staff 4096 Jan 14 09:15 Projects
lrwxrwxrwx 1 alice staff 15 Jan 13 08:00 link -> /tmp/file
Let's decode each column:
-rw-r--r-- 1 alice staff 4096 Jan 15 10:30 document.txt
ββββ€βββ€βββ€ β β β β β β
β β β β β β β β β ββ Filename
β β β β β β β β ββ Last modified date/time
β β β β β β β ββ Size in bytes
β β β β β β ββ Group owner
β β β β β ββ User owner
β β β β ββ Number of hard links
β β β ββ Others permissions (read, no write, no execute)
β β ββ Group permissions (read, no write, no execute)
β ββ Owner permissions (read, write, no execute)
ββ File type
File Types (First Character)
| Character | Type | Example |
|---|---|---|
- | Regular file | -rw-r--r-- document.txt |
d | Directory | drwxr-xr-x Projects/ |
l | Symbolic link | lrwxrwxrwx link -> target |
c | Character device | crw-rw-rw- /dev/tty |
b | Block device | brw-rw---- /dev/sda1 |
p | Named pipe (FIFO) | prw-r--r-- pipe |
s | Socket | srwxrwxrwx socket |
Permission Characters
Permissions are shown as 9 characters in 3 groups of 3:
rwxr-xr-x
βββββββββ
βββββ¬βββ¬β
βββ β ββ Others: read + execute
βββ ββ Group: read + execute
βββ΄β Owner: read + write + execute
| Character | Meaning | For Files | For Directories |
|---|---|---|---|
r | Read | View file contents | List directory contents |
w | Write | Modify file | Create/delete files in directory |
x | Execute | Run as program | Enter directory (cd) |
- | No permission | Cannot perform action | Cannot perform action |
Essential ls Options
# Human-readable sizes (KB, MB, GB instead of bytes)
ls -lh
# Output: -rw-r--r-- 1 alice staff 4.0K Jan 15 10:30 document.txt
# Sort by modification time (newest first)
ls -lt
# Sort by modification time (oldest first)
ls -ltr
# Sort by size (largest first)
ls -lS
# Sort by size (smallest first)
ls -lSr
# Recursive (show contents of subdirectories)
ls -R
# Show only directories
ls -d */
# One file per line (useful for scripting)
ls -1
# Show file type indicators
ls -F
# / = directory, * = executable, @ = symlink, | = pipe
# All files, long format, human-readable, sorted by time
ls -alht
# List with full timestamps
ls -l --time-style=full-iso
# List inode numbers (useful for debugging hard links)
ls -li
# List with colors (usually aliased by default)
ls --color=autoPractical ls Examples
# Find the largest files in a directory
ls -lhS /var/log | head -10
# Find recently modified files
ls -lt ~/Documents | head -10
# See hidden configuration files in your home directory
ls -la ~ | grep '^\.'
# Count files in a directory
ls -1 /etc | wc -l
# List only .txt files
ls -la *.txt
# List files matching a pattern
ls -la report_202*.pdf
# Show directory size summaries with du instead
ls -lh --block-size=M
du -sh */ # Better for directory sizes
# List files modified in the last 24 hours
ls -lt | grep "$(date '+%b %e')"
# List files by extension, sorted
ls -la | grep '\.txt$' | sortWildcards (Globbing)
Wildcards (also called "globbing") let you match multiple files at once using patterns. The shell expands these patterns before passing them to commands.
Basic Wildcards
| Wildcard | Meaning | Example | Matches |
|---|---|---|---|
* | Any number of any characters | *.txt | file.txt, document.txt, report_2024.txt |
? | Exactly one character | file?.txt | file1.txt, fileA.txt (not file10.txt) |
[abc] | One character from the set | file[123].txt | file1.txt, file2.txt, file3.txt |
[a-z] | One character from the range | file[a-z].txt | filea.txt through filez.txt |
[!abc] | One character NOT in the set | file[!0-9].txt | fileA.txt (not file1.txt) |
Advanced Wildcards (Bash Extended Globbing)
Enable with shopt -s extglob:
| Pattern | Meaning | Example |
|---|---|---|
?(pattern) | Zero or one occurrence | file?(s).txt matches file.txt, files.txt |
*(pattern) | Zero or more occurrences | file*([0-9]).txt matches file.txt, file1.txt, file123.txt |
+(pattern) | One or more occurrences | file+([0-9]).txt matches file1.txt, file123.txt (not file.txt) |
@(pattern) | Exactly one occurrence | @(file|doc).txt matches file.txt or doc.txt |
!(pattern) | Anything except pattern | !(*.log) matches everything except .log files |
Brace Expansion
# Create multiple files at once
touch file{1,2,3}.txt
# Creates: file1.txt, file2.txt, file3.txt
# Numeric ranges
touch file{1..10}.txt
# Creates: file1.txt through file10.txt
# Alphabetic ranges
mkdir dir{a..z}
# Creates: dira, dirb, ..., dirz
# Combine patterns
touch {report,memo,letter}_{2024..2026}.{txt,pdf}
# Creates: report_2024.txt, report_2024.pdf, report_2025.txt, etc.Wildcard Examples
# All text files in current directory
ls *.txt
# All files starting with "report"
ls report*
# Files like data1.csv, data2.csv, ... data9.csv
ls data?.csv
# All CSV files
ls *.csv
# Files with a vowel as second character
ls ?[aeiou]*
# JPEG and PNG images
ls *.{jpg,png,gif}
ls *.jpg *.png *.gif # Same thing
# All files except .log files (requires extglob)
shopt -s extglob
ls !(*.log)
# All Python files in all subdirectories (requires globstar)
shopt -s globstar
ls **/*.py
# Files modified today
ls -l *.txt | grep "$(date '+%b %e')"
# Backup all .conf files
cp /etc/*.conf ~/backup/
# Remove all temporary files
rm /tmp/temp_*β οΈ Wildcards expand before command execution
The shell expands wildcards BEFORE running the command. This means:
ls *.txt
# Shell expands to: ls file1.txt file2.txt file3.txt
# Then runs ls with those arguments
# If no matches, you get an error:
ls *.xyz
# bash: No such file or directoryThis is different from some other systems where the command does the expansion.
tree β Visual Directory Structure
The tree command shows a visual, hierarchical representation of directory structure. It's not always installed by default but is incredibly useful.
Installing tree
# Ubuntu/Debian
sudo apt install tree
# macOS
brew install tree
# Fedora/RHEL/CentOS
sudo dnf install treeUsing tree
# Basic usage (show everything in current directory)
tree
# Limit depth to 2 levels
tree -L 2
# Show only directories (no files)
tree -d
# Show hidden files
tree -a
# Show file sizes
tree -h
# Show file sizes with units
tree -sh
# Show only specific file types
tree -P "*.py" # Only Python files
tree -P "*.{js,ts}" # JavaScript and TypeScript files
# Exclude patterns
tree -I "node_modules|__pycache__|*.pyc"
# Show full path for each file
tree -f
# Sort by modification time
tree -t
# Show permissions
tree -p
# Combine options
tree -L 3 -h -a --dirsfirstExample tree Output
tree -L 2 ~/Projects/my-appOutput:
/home/alice/Projects/my-app
βββ README.md
βββ package.json
βββ src/
β βββ index.js
β βββ components/
β βββ utils/
βββ tests/
β βββ unit/
β βββ integration/
βββ docs/
β βββ api.md
βββ node_modules/
βββ express/
βββ lodash/
7 directories, 4 files
Why tree is useful:
- Project overview: Quickly understand project structure
- Documentation: Include in README files to show layout
- Debugging: Find where files are located
- Teaching: Show filesystem concepts visually
Additional Navigation Commands
file β Identify File Types
Linux doesn't rely on file extensions to determine file type. The file command examines the actual contents:
file document.txt
# document.txt: UTF-8 Unicode text
file photo.jpg
# photo.jpg: JPEG image data, JFIF standard 1.01
file script.sh
# script.sh: Bash script, ASCII text executable
file /bin/ls
# /bin/ls: ELF 64-bit LSB pie executable, x86-64
file archive.tar.gz
# archive.tar.gz: gzip compressed data
file mystery_file
# Tells you what it actually is, regardless of name or extension
# Check multiple files
file *
# Be brief (just show type)
file -b document.txt
# UTF-8 Unicode text
# Show MIME type (useful for web servers)
file -i document.txt
# document.txt: text/plain; charset=utf-8Why this matters: Files can be misnamed or have no extension. file examines the actual content to determine type.
stat β Detailed File Information
The stat command shows comprehensive file metadata:
stat document.txtOutput:
File: document.txt
Size: 4096 Blocks: 8 IO Block: 4096 regular file
Device: 802h/2050d Inode: 1234567 Links: 1
Access: (0644/-rw-r--r--) Uid: (1000/alice) Gid: (1000/staff)
Access: 2024-01-15 10:30:00.000000000 +0000
Modify: 2024-01-15 10:30:00.000000000 +0000
Change: 2024-01-15 10:30:00.000000000 +0000
Birth: 2024-01-14 08:00:00.000000000 +0000
Key information:
- Size: File size in bytes
- Blocks: Disk blocks used (filesystem-dependent)
- Inode: Unique identifier for this file on the filesystem
- Links: Number of hard links pointing to this file
- Access time: Last time file was read
- Modify time: Last time file content was changed
- Change time: Last time file metadata (permissions, ownership) was changed
- Birth time: When file was created (if filesystem supports it)
# Just show modification time (useful in scripts)
stat -c %Y document.txt
# 1705317000
# Human-readable format
stat -c "%n: %s bytes, modified %y" document.txt
# document.txt: 4096 bytes, modified 2024-01-15 10:30:00.000000000 +0000basename and dirname
Extract parts of paths:
# Get just the filename (remove directory path)
basename /home/alice/Documents/report.txt
# report.txt
# Get just the filename without extension
basename /home/alice/Documents/report.txt .txt
# report
# Get just the directory path (remove filename)
dirname /home/alice/Documents/report.txt
# /home/alice/DocumentsUseful in scripts:
# Process all files in a directory
for file in /var/log/*.log; do
filename=$(basename "$file")
dir=$(dirname "$file")
echo "Processing $filename in $dir"
doneExercises
Complete these navigation tasks in your terminal:
Task 1: Starting from your home directory, navigate to /tmp, then to /etc, then back to your home directory using only cd - and cd ~.
π‘ Hint
cd /tmp, then cd /etc, then cd ~ to go home. Try cd - to toggle between the last two directories.Show Solution
cd ~ # Start at home
pwd # /home/username
cd /tmp # Go to /tmp
pwd # /tmp
cd /etc # Go to /etc
pwd # /etc
cd - # Back to /tmp (toggles to previous directory)
pwd # /tmp
cd - # Back to /etc
pwd # /etc
cd ~ # Go home
pwd # /home/username
# Bonus: cd without arguments also goes home
cd
pwd # /home/usernameTask 2: List all files (including hidden) in your home directory in long format with human-readable sizes, sorted by modification time (newest first).
Show Solution
ls -laht ~
# -l: long format (permissions, owner, size, date)
# -a: all files (including hidden files starting with .)
# -h: human-readable sizes (KB, MB, GB instead of bytes)
# -t: sort by modification time (newest first)
# Sample output:
# drwxr-xr-x 25 alice staff 800B Jan 15 10:35 .
# -rw-r--r-- 1 alice staff 1.2K Jan 15 10:30 .bashrc
# -rw-r--r-- 1 alice staff 4.0K Jan 14 09:15 document.txt
# drwxr-xr-x 5 alice staff 160B Jan 13 08:00 DocumentsTask 3: Using wildcards, list all .conf files in /etc (you may need sudo for some directories).
Show Solution
# List .conf files directly in /etc
ls /etc/*.conf
# Common output:
# /etc/host.conf /etc/nsswitch.conf /etc/resolv.conf
# For recursive search including subdirectories:
ls /etc/**/*.conf 2>/dev/null # Requires: shopt -s globstar
# The 2>/dev/null suppresses permission errors
# Or better yet, use find:
find /etc -name "*.conf" 2>/dev/null | head -20
# This searches all subdirectories and handles permissions gracefullyTask 4: Show the directory tree of /etc but only 2 levels deep, directories only.
Show Solution
tree -L 2 -d /etc
# -L 2: limit to 2 levels deep
# -d: directories only (no files)
# Sample output:
# /etc
# βββ alternatives
# βββ apache2
# β βββ conf-available
# β βββ conf-enabled
# β βββ mods-available
# β βββ mods-enabled
# βββ apt
# β βββ apt.conf.d
# β βββ preferences.d
# β βββ sources.list.d
# βββ systemd
# βββ system
# βββ user
# If tree is not installed:
# Ubuntu/Debian: sudo apt install tree
# macOS: brew install treeGiven this directory structure:
/home/alice/
βββ Documents/
β βββ work/
β β βββ report.txt
β β βββ data.csv
β βββ personal/
β βββ diary.txt
βββ Downloads/
β βββ photo.jpg
βββ .bashrc
Q1: If you are in /home/alice/Documents/work/, what is the relative path to diary.txt?
Show Solution
../personal/diary.txt
Explanation:
..goes up one level to/home/alice/Documents/- Then
personal/diary.txtgoes down intopersonal/and findsdiary.txt - The path is relative to your current location (
/home/alice/Documents/work/)
Q2: If you are in /home/alice/Downloads/, what is the relative path to report.txt?
Show Solution
../Documents/work/report.txt
Explanation:
..goes up one level to/home/alice/- Then
Documents/work/report.txtgoes down throughDocuments/, intowork/, and findsreport.txt
Q3: What command would show all hidden files in alice's home directory?
Show Solution
ls -la /home/alice
# or if you're alice:
ls -la ~
# or just:
ls -la
# The -a flag shows "all" files, including hidden ones
# Hidden files start with a dot (.), like .bashrc, .bash_history, .ssh/
# To show ONLY hidden files:
ls -ld ~/.[^.]*
# This pattern matches files starting with . but not .. (parent directory)Q4: Write a command that lists only directories in the current location.
Show Solution
# Method 1: Using ls with wildcard
ls -ld */
# Method 2: Using ls with grep
ls -l | grep '^d'
# Method 3: Using find
find . -maxdepth 1 -type d
# Method 4: Using tree
tree -L 1 -d
# The simplest and most reliable: ls -ld */
# The */ wildcard matches only directoriesPractice these wildcard patterns (create test files first):
# Setup: Create test files
cd /tmp
mkdir wildcard-practice
cd wildcard-practice
touch file1.txt file2.txt file10.txt fileA.txt
touch report_2023.pdf report_2024.pdf report_2025.doc
touch image1.jpg image2.png photo.gifTask 1: List only files that end with .txt and have a single digit in the name.
Show Solution
ls file?.txt
# Matches: file1.txt, file2.txt, fileA.txt
# Does NOT match: file10.txt (two digits)
# To match only numeric digits:
ls file[0-9].txt
# Matches: file1.txt, file2.txt
# Does NOT match: fileA.txtTask 2: List all PDF files from 2024 or later.
Show Solution
ls report_202[4-5].pdf
# Matches: report_2024.pdf, report_2025.pdf
# Does NOT match: report_2023.pdf
# Or for any year starting with 202:
ls report_202*.pdf
# Matches: report_2023.pdf, report_2024.pdf, report_2025.pdfTask 3: List all image files (jpg, png, gif).
Show Solution
# Method 1: Brace expansion
ls *.{jpg,png,gif}
# Matches: image1.jpg, image2.png, photo.gif
# Method 2: Multiple wildcards
ls *.jpg *.png *.gif
# Method 3: Extended globbing (requires shopt -s extglob)
shopt -s extglob
ls *.@(jpg|png|gif)Task 4: Delete all files EXCEPT .txt files.
Show Solution
# DANGER: Test with ls first before using rm!
# Enable extended globbing
shopt -s extglob
# List files to be deleted (SAFE - test first!)
ls !(*.txt)
# Shows: report_2023.pdf, report_2024.pdf, report_2025.doc,
# image1.jpg, image2.png, photo.gif
# If that looks correct, delete them:
rm !(*.txt)
# Verify:
ls
# Should show only: file1.txt, file2.txt, file10.txt, fileA.txtAlways test wildcard patterns with ls before using them with destructive commands like rm!
Summary
Mastering filesystem navigation is the foundation of Linux command-line proficiency:
- Directory structure: Linux follows FHS; understanding
/,/etc,/home,/varhelps you know where things are - Paths: Absolute paths start with
/, relative paths don't; use~for home,..for parent,.for current - pwd: Shows your current directoryβyour GPS in the terminal
- cd: Changes directoryβuse Tab completion religiously to save typing
- ls: Lists directory contentsβmaster
-l,-a,-h,-t,-Soptions - Wildcards:
*(any characters),?(one character),[abc](character set) match multiple files - tree: Visualizes directory structure (install separately)
- file: Identifies file types by content, not extension
- stat: Shows detailed file metadata
Practice these commands daily. Navigation becomes muscle memory quickly, and soon you'll be flying through directories faster than any GUI file manager could take you.
In the next tutorial, you'll learn to actually do things with filesβcreate, copy, move, delete, and manage permissions.