> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Linux Fundamentals

> Master the Linux command line and file system

# Linux Fundamentals

Master the essential Linux commands and file system navigation that every developer needs.

<img src="https://mintcdn.com/devweeekends/emzPt-9B_R8UKdqm/images/courses/devops-tools/linux-filesystem.svg?fit=max&auto=format&n=emzPt-9B_R8UKdqm&q=85&s=f88d255bc7c78c296d58948ebe9177b4" alt="Linux File System" width="1080" height="1080" data-path="images/courses/devops-tools/linux-filesystem.svg" />

***

## The Linux File System

Everything in Linux starts from the root directory `/`. Unlike Windows (where you might have C:, D:, E:\ as separate drive letters), Linux has a single tree. Everything -- every file, device, process, and even hardware interface -- hangs off that one root. Plug in a USB drive? It gets mounted somewhere in this tree. Check CPU info? It is a file in this tree.

### Key Directories

```bash theme={null}
/           # Root - the top of the entire hierarchy, everything branches from here
/home       # User home directories (/home/alice, /home/bob) -- personal files and configs
/etc        # System-wide configuration files (nginx.conf, ssh config, hostname, etc.)
/var        # Variable data that changes at runtime (logs in /var/log, databases, web content)
/usr        # User-installed programs and libraries (most of your installed software lives here)
/bin        # Essential command binaries (ls, cp, mv, cat) -- available even in single-user mode
/sbin       # System binaries that typically require root (fdisk, iptables, reboot)
/tmp        # Temporary files -- cleared on reboot, writable by everyone (be careful what you store here)
/opt        # Optional/third-party software installed outside the package manager
/dev        # Device files -- hardware represented as files (/dev/sda = first disk, /dev/null = black hole)
/proc       # Virtual filesystem exposing kernel and process info (/proc/cpuinfo, /proc/meminfo)
```

***

## Navigation Commands

```bash theme={null}
# Print working directory
pwd

# List files
ls              # Basic listing
ls -l           # Long format (permissions, size, date)
ls -a           # Show hidden files
ls -lh          # Human-readable sizes
ls -lah         # All options combined

# Change directory
cd /var/log     # Absolute path
cd logs         # Relative path
cd ..           # Parent directory
cd ~            # Home directory
cd -            # Previous directory

# Show directory tree
tree            # Install with: apt install tree
tree -L 2       # Limit depth to 2 levels
```

***

## File Operations

### Creating Files and Directories

```bash theme={null}
# Create an empty file (or update the timestamp of an existing file)
# touch is like tapping a file to say "I was here" -- it creates it if missing
touch file.txt

# Create a directory
mkdir mydir

# Create nested directories (the -p flag creates all missing parents)
# Without -p, this fails if "path" or "path/to" do not already exist
mkdir -p path/to/nested/dir

# Create multiple directories at once
mkdir dir1 dir2 dir3

# Brace expansion lets you create a project structure in one command
mkdir -p project/{src,tests,docs,config}
```

### Copying and Moving

```bash theme={null}
# Copy files
cp source.txt dest.txt
cp -r sourcedir/ destdir/    # Copy directory recursively
cp -i file.txt backup.txt    # Interactive (prompt before overwrite)

# Move/rename
mv oldname.txt newname.txt
mv file.txt /path/to/destination/
mv *.txt documents/          # Move all .txt files
```

### Deleting

```bash theme={null}
# Remove a single file
rm file.txt
rm -i file.txt    # Interactive -- asks "are you sure?" before each deletion
rm -f file.txt    # Force -- no confirmation prompt, ignores missing files

# Remove directories and everything inside them
rm -r directory/  # Recursive -- required for non-empty directories
rm -rf directory/ # Force recursive -- deletes everything without asking (DANGEROUS)

# Remove only empty directories (safe alternative when you expect them to be empty)
rmdir emptydir/
```

<Warning>
  **There is no recycle bin in Linux.** When `rm` deletes a file, it is gone. There is no undo, no trash folder, no recovery tool (without specialized forensic software). Be especially careful with `rm -rf` combined with variables -- `rm -rf $DIR/` where `$DIR` is accidentally empty expands to `rm -rf /`, which attempts to delete your entire filesystem. Always double-check before pressing Enter.
</Warning>

***

## Viewing File Contents

```bash theme={null}
# Display entire file
cat file.txt

# Display with line numbers
cat -n file.txt

# Concatenate multiple files
cat file1.txt file2.txt > combined.txt

# Page through file
less file.txt    # Use arrows, q to quit
more file.txt    # Older pager

# First/last lines
head file.txt         # First 10 lines
head -n 20 file.txt   # First 20 lines
tail file.txt         # Last 10 lines
tail -n 50 file.txt   # Last 50 lines
tail -f /var/log/syslog  # Follow file updates (live)

# Word count
wc file.txt           # Lines, words, bytes
wc -l file.txt        # Just line count
```

***

## Finding Files

### Using `find`

```bash theme={null}
# Find by name
find /path -name "*.txt"
find . -name "config.json"

# Find by type
find /var -type f    # Files only
find /var -type d    # Directories only

# Find by size
find . -size +100M   # Larger than 100MB
find . -size -1k     # Smaller than 1KB

# Find and execute
find . -name "*.log" -delete
find . -name "*.txt" -exec cat {} \;

# Find modified in last 7 days
find . -mtime -7
```

### Using `locate`

```bash theme={null}
# Fast file search (uses a pre-built database -- instant results even on huge filesystems)
# The trade-off: results may be stale because the database is only updated periodically
locate filename

# Update the database manually (usually runs nightly via cron)
# Run this after creating new files if you need locate to find them immediately
sudo updatedb

# Case-insensitive search
locate -i filename
```

<Tip>
  **When to use `find` vs `locate`**: Use `find` when you need real-time, accurate results (it scans the actual filesystem). Use `locate` when speed matters and slightly stale results are acceptable (it searches a pre-built index). On a server with millions of files, `find /` can take minutes while `locate` returns instantly.
</Tip>

### Using `grep` to search inside files

```bash theme={null}
# Search for text in file
grep "error" logfile.txt

# Case-insensitive
grep -i "error" logfile.txt

# Recursive search in directory
grep -r "TODO" /path/to/code/

# Show line numbers
grep -n "error" logfile.txt

# Count matches
grep -c "error" logfile.txt

# Invert match (lines NOT containing pattern)
grep -v "success" logfile.txt
```

***

## File Permissions Preview

```bash theme={null}
# View permissions
ls -l

# Output format:
# -rw-r--r-- 1 user group 1234 Dec 2 10:00 file.txt
# │││││││││
# │││││││└└ Other permissions (read, write, execute)
# ││││││└└└ Group permissions
# │││└└└└└└ Owner permissions
# ││└─────── Number of links
# │└──────── File type (- = file, d = directory)
```

We'll cover permissions in detail in the next module.

***

## Practical Examples

### Example 1: Organizing Files

```bash theme={null}
# Create project structure
mkdir -p project/{src,docs,tests}
cd project

# Create files
touch src/main.py src/utils.py
touch docs/README.md
touch tests/test_main.py

# View structure
tree
```

### Example 2: Finding Large Files

```bash theme={null}
# Find files larger than 100MB
find /home -type f -size +100M -exec ls -lh {} \; 2>/dev/null

# Or use du
du -h /home | sort -rh | head -20
```

### Example 3: Searching Logs

```bash theme={null}
# Find errors in log file
grep -i "error" /var/log/syslog

# Count error occurrences
grep -c "error" /var/log/syslog

# Show errors with context
grep -C 3 "error" /var/log/syslog  # 3 lines before and after
```

***

## Useful Shortcuts

```bash theme={null}
# Tab completion
cd /var/l[TAB]  # Completes to /var/log

# Command history
history         # Show command history
!123            # Run command #123 from history
!!              # Run last command
!$              # Last argument of previous command

# Ctrl shortcuts
Ctrl+C          # Cancel current command
Ctrl+D          # Exit shell
Ctrl+L          # Clear screen
Ctrl+R          # Search command history
Ctrl+A          # Move to beginning of line
Ctrl+E          # Move to end of line
```

***

## Wildcards and Patterns

```bash theme={null}
# * matches any characters
ls *.txt        # All .txt files
rm file*        # All files starting with "file"

# ? matches single character
ls file?.txt    # file1.txt, fileA.txt, etc.

# [] matches character range
ls file[1-3].txt    # file1.txt, file2.txt, file3.txt
ls [A-Z]*.txt       # Files starting with capital letter

# {} for multiple patterns
cp file.{txt,md} backup/  # Copy file.txt and file.md
```

***

## Redirection and Pipes

Redirection and pipes are what make the Linux command line so powerful. Each command has three standard streams: **stdin** (input, fd 0), **stdout** (output, fd 1), and **stderr** (errors, fd 2). Redirection lets you reroute these streams to files. Pipes let you connect the output of one command to the input of another, building powerful data processing pipelines.

```bash theme={null}
# Output redirection
echo "Hello" > file.txt     # Write to file (overwrites existing content)
echo "World" >> file.txt    # Append to file (preserves existing content)

# Input redirection -- feed a file's contents as stdin to a command
wc -l < file.txt

# Pipes -- connect stdout of one command to stdin of the next
# Think of it as an assembly line: each command processes the data and passes it along
cat file.txt | grep "error" | wc -l   # Count lines containing "error"
ls -l | less                            # Page through a long file listing
ps aux | grep python                    # Find running Python processes

# Redirect stderr (error messages) to a file
command 2> error.log                   # Errors go to file, normal output still prints to screen
command > output.log 2>&1              # Both stdout AND stderr go to the same file
command > /dev/null 2>&1               # Discard all output entirely (useful in cron jobs)
```

<Tip>
  **The pipe is the most important concept here.** Linux follows a philosophy of small, focused tools. `grep` searches, `sort` sorts, `wc` counts, `head` takes the first N lines. Individually they are simple. Piped together, they solve complex problems: `cat access.log | grep "500" | awk '{print $1}' | sort | uniq -c | sort -rn | head -10` gives you the top 10 IP addresses causing 500 errors.
</Tip>

***

## Key Takeaways

* Linux file system starts at `/` (root)
* Use `ls`, `cd`, `pwd` for navigation
* `cp`, `mv`, `rm` for file operations
* `cat`, `less`, `head`, `tail` to view files
* `find` and `grep` to search
* Tab completion and history save time
* Pipes (`|`) chain commands together

***

Next: [Linux Permissions & Users →](/courses/devops-tools/linux-permissions)
