Master Linux Basics with Daily Practice
Table of Contents
1. [Introduction to Linux](#introduction-to-linux) 2. [File System Navigation](#file-system-navigation) 3. [File and Directory Operations](#file-and-directory-operations) 4. [Text Processing and Manipulation](#text-processing-and-manipulation) 5. [Process Management](#process-management) 6. [System Information and Monitoring](#system-information-and-monitoring) 7. [Network Commands](#network-commands) 8. [File Permissions and Ownership](#file-permissions-and-ownership) 9. [Package Management](#package-management) 10. [Advanced Commands and Concepts](#advanced-commands-and-concepts) 11. [Daily Practice Routine](#daily-practice-routine)Introduction to Linux
Linux is a powerful, open-source operating system that forms the backbone of countless servers, embedded systems, and desktop computers worldwide. Understanding Linux fundamentals is essential for system administrators, developers, and IT professionals. The command-line interface provides direct control over system operations and enables automation through scripting.
The Linux file system follows a hierarchical structure starting from the root directory (/). Unlike Windows, Linux treats everything as a file, including hardware devices, processes, and system resources. This unified approach simplifies system management and provides consistent interfaces for various operations.
Key Linux Concepts
| Concept | Description | Example | |---------|-------------|---------| | Root Directory | Top-level directory in Linux hierarchy | / | | Home Directory | User's personal directory | /home/username | | Working Directory | Current directory location | pwd command shows current location | | Path | Location specification for files/directories | /usr/local/bin/program | | Shell | Command interpreter interface | bash, zsh, fish |
File System Navigation
Navigation forms the foundation of Linux command-line proficiency. Understanding how to move through directories efficiently enables all other operations.
Essential Navigation Commands
#### pwd (Print Working Directory)
`bash
pwd
`
Purpose: Displays the absolute path of current directory
Output Example: /home/user/documents
#### cd (Change Directory)
`bash
cd /path/to/directory # Absolute path navigation
cd relative/path # Relative path navigation
cd .. # Move to parent directory
cd ~ # Move to home directory
cd - # Return to previous directory
`
Notes: - Absolute paths start with forward slash (/) - Relative paths are relative to current directory - Tilde (~) represents user home directory - Dash (-) toggles between current and previous directory
#### ls (List Directory Contents)
`bash
ls # Basic listing
ls -l # Long format with details
ls -la # Include hidden files
ls -lh # Human-readable file sizes
ls -lt # Sort by modification time
ls -lr # Reverse order listing
`
Long Format Explanation:
`
-rw-r--r-- 1 user group 1024 Jan 15 10:30 filename
│││││││││ │ │ │ │ │ │
│││││││││ │ │ │ │ │ └─ filename
│││││││││ │ │ │ │ └─ modification time
│││││││││ │ │ │ └─ file size
│││││││││ │ │ └─ group ownership
│││││││││ │ └─ user ownership
│││││││││ └─ number of links
└─────────── file permissions
`
Directory Structure Overview
| Directory | Purpose | Contents | |-----------|---------|----------| | / | Root directory | System foundation | | /home | User directories | Personal files and settings | | /etc | Configuration files | System and application configs | | /var | Variable data | Logs, databases, temporary files | | /usr | User programs | Applications and utilities | | /bin | Essential binaries | Core system commands | | /sbin | System binaries | Administrative commands | | /tmp | Temporary files | Temporary storage | | /opt | Optional software | Third-party applications | | /proc | Process information | Virtual filesystem for processes |
File and Directory Operations
File and directory manipulation represents core Linux functionality. These operations enable creation, modification, and organization of data.
Creating Files and Directories
#### touch (Create Empty Files)
`bash
touch filename.txt # Create single file
touch file1.txt file2.txt # Create multiple files
touch /path/to/new/file.txt # Create with full path
`
Notes: - Creates empty file if it doesn't exist - Updates timestamp if file exists - Useful for creating placeholder files
#### mkdir (Make Directories)
`bash
mkdir directory_name # Create single directory
mkdir dir1 dir2 dir3 # Create multiple directories
mkdir -p path/to/nested/dirs # Create nested directories
mkdir -m 755 secure_dir # Create with specific permissions
`
Options Explanation:
- -p: Creates parent directories if they don't exist
- -m: Sets directory permissions during creation
Copying and Moving Operations
#### cp (Copy Files and Directories)
`bash
cp source.txt destination.txt # Copy file
cp source.txt /path/to/destination/ # Copy to directory
cp -r source_dir destination_dir # Copy directory recursively
cp -i source.txt destination.txt # Interactive mode (prompt before overwrite)
cp -u source.txt destination.txt # Update mode (copy if newer)
`
Important Options:
- -r or -R: Recursive copy for directories
- -i: Interactive mode for safety
- -u: Update only if source is newer
- -v: Verbose output showing operations
#### mv (Move/Rename Files)
`bash
mv oldname.txt newname.txt # Rename file
mv file.txt /path/to/destination/ # Move file to directory
mv directory_old directory_new # Rename directory
mv *.txt /backup/ # Move multiple files using wildcards
`
Notes:
- Single command for both moving and renaming
- Works with both files and directories
- Automatically overwrites unless using -i option
Removing Files and Directories
#### rm (Remove Files and Directories)
`bash
rm filename.txt # Remove single file
rm file1.txt file2.txt # Remove multiple files
rm -i filename.txt # Interactive removal
rm -r directory_name # Remove directory recursively
rm -rf directory_name # Force remove without prompts
`
Critical Safety Notes:
- -r: Required for directory removal
- -f: Forces removal without prompts (dangerous)
- -i: Prompts before each removal (safer)
- No built-in recovery mechanism - deletions are permanent
#### rmdir (Remove Empty Directories)
`bash
rmdir empty_directory # Remove single empty directory
rmdir -p path/to/empty/nested/dirs # Remove nested empty directories
`
File Content Operations
#### cat (Display File Contents)
`bash
cat filename.txt # Display entire file
cat file1.txt file2.txt # Display multiple files
cat -n filename.txt # Display with line numbers
cat -b filename.txt # Number non-empty lines only
`
#### less and more (Paginated File Viewing)
`bash
less filename.txt # View file with navigation
more filename.txt # Simple paginated viewing
`
less Navigation: - Space: Next page - b: Previous page - /pattern: Search forward - ?pattern: Search backward - q: Quit
#### head and tail (Partial File Display)
`bash
head filename.txt # First 10 lines
head -n 20 filename.txt # First 20 lines
tail filename.txt # Last 10 lines
tail -n 15 filename.txt # Last 15 lines
tail -f logfile.txt # Follow file changes (useful for logs)
`
Text Processing and Manipulation
Text processing capabilities make Linux powerful for data manipulation and system administration tasks.
Search and Pattern Matching
#### grep (Global Regular Expression Print)
`bash
grep "pattern" filename.txt # Search for pattern in file
grep -i "pattern" filename.txt # Case-insensitive search
grep -r "pattern" directory/ # Recursive search in directory
grep -n "pattern" filename.txt # Show line numbers
grep -v "pattern" filename.txt # Invert match (exclude pattern)
grep -c "pattern" filename.txt # Count matching lines
`
Advanced grep Examples:
`bash
grep "^start" file.txt # Lines starting with "start"
grep "end$" file.txt # Lines ending with "end"
grep -E "pattern1|pattern2" file.txt # Multiple patterns (extended regex)
grep -A 3 -B 2 "pattern" file.txt # Show 3 lines after, 2 lines before match
`
#### find (Locate Files and Directories)
`bash
find /path -name "filename" # Find by name
find /path -name "*.txt" # Find by pattern
find /path -type f # Find files only
find /path -type d # Find directories only
find /path -size +100M # Find files larger than 100MB
find /path -mtime -7 # Find files modified in last 7 days
`
Complex find Examples:
`bash
find /home -name "*.log" -size +10M -delete # Find and delete large log files
find /tmp -type f -atime +30 -exec rm {} \; # Remove files not accessed in 30 days
`
Text Manipulation Tools
#### sed (Stream Editor)
`bash
sed 's/old/new/' filename.txt # Replace first occurrence per line
sed 's/old/new/g' filename.txt # Replace all occurrences
sed -i 's/old/new/g' filename.txt # Edit file in-place
sed '1,5s/old/new/g' filename.txt # Replace in lines 1-5 only
sed '/pattern/d' filename.txt # Delete lines matching pattern
`
#### awk (Text Processing Language)
`bash
awk '{print $1}' filename.txt # Print first column
awk '{print $1, $3}' filename.txt # Print first and third columns
awk '/pattern/ {print $0}' filename.txt # Print lines matching pattern
awk '{sum+=$1} END {print sum}' data.txt # Sum first column values
`
#### sort and uniq (Data Organization)
`bash
sort filename.txt # Sort lines alphabetically
sort -n numbers.txt # Numerical sort
sort -r filename.txt # Reverse sort
sort -k 2 data.txt # Sort by second column
uniq filename.txt # Remove duplicate adjacent lines
sort filename.txt | uniq # Sort then remove duplicates
sort filename.txt | uniq -c # Count occurrences of each line
`
Input/Output Redirection
#### Redirection Operators
| Operator | Purpose | Example | |----------|---------|---------| | > | Redirect output to file (overwrite) | ls > filelist.txt | | >> | Redirect output to file (append) | echo "text" >> file.txt | | < | Redirect input from file | sort < unsorted.txt | | \| | Pipe output to another command | ls \| grep ".txt" | | 2> | Redirect error output | command 2> errors.txt | | &> | Redirect both output and errors | command &> all_output.txt |
#### Practical Redirection Examples
`bash
ls -la > directory_listing.txt # Save directory listing to file
cat file1.txt file2.txt > combined.txt # Combine files
grep "error" /var/log/syslog >> errors.log # Append errors to log file
command 2>/dev/null # Discard error messages
`
Process Management
Understanding process management enables effective system resource utilization and troubleshooting.
Process Viewing and Monitoring
#### ps (Process Status)
`bash
ps # Show current user processes
ps aux # Show all processes with details
ps -ef # Alternative detailed format
ps -u username # Show processes for specific user
ps -C program_name # Show processes by command name
`
ps aux Output Explanation:
`
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 19696 1234 ? Ss Jan15 0:01 /sbin/init
│ │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │ └─ command
│ │ │ │ │ │ │ │ │ └─ CPU time used
│ │ │ │ │ │ │ │ └─ start time
│ │ │ │ │ │ │ └─ process state
│ │ │ │ │ │ └─ terminal
│ │ │ │ │ └─ resident memory (KB)
│ │ │ │ └─ virtual memory (KB)
│ │ │ └─ memory percentage
│ │ └─ CPU percentage
│ └─ process ID
└─ user owner
`
#### top and htop (Real-time Process Monitoring)
`bash
top # Real-time process viewer
htop # Enhanced process viewer (if installed)
`
top Interactive Commands: - q: Quit - k: Kill process - r: Renice process - M: Sort by memory usage - P: Sort by CPU usage - u: Filter by user
Process Control
#### Background and Foreground Jobs
`bash
command & # Run command in background
jobs # List active jobs
fg %1 # Bring job 1 to foreground
bg %1 # Send job 1 to background
Ctrl+Z # Suspend current foreground job
`
#### Process Termination
#### kill (Terminate Processes)
`bash
kill PID # Terminate process by ID
kill -9 PID # Force kill process
kill -15 PID # Graceful termination (SIGTERM)
killall program_name # Kill all processes by name
pkill -f "pattern" # Kill processes matching pattern
`
Common Kill Signals:
| Signal | Number | Purpose | |--------|--------|---------| | SIGTERM | 15 | Graceful termination (default) | | SIGKILL | 9 | Force termination | | SIGHUP | 1 | Hang up signal | | SIGINT | 2 | Interrupt (Ctrl+C) | | SIGSTOP | 19 | Stop process |
System Information and Monitoring
System monitoring commands provide insights into hardware resources, system performance, and operational status.
System Resource Monitoring
#### System Load and Performance
`bash
uptime # System uptime and load average
free -h # Memory usage (human-readable)
df -h # Disk space usage
du -sh directory/ # Directory size summary
iostat # I/O statistics
vmstat # Virtual memory statistics
`
Load Average Explanation: Load averages show system load over 1, 5, and 15-minute intervals. Values represent average number of processes either running or waiting for resources.
#### Hardware Information
`bash
lscpu # CPU information
lsblk # Block device information
lsusb # USB device information
lspci # PCI device information
dmidecode # Hardware DMI information
`
#### System Information Commands
| Command | Purpose | Example Output | |---------|---------|----------------| | uname -a | Complete system information | Linux hostname 5.4.0 x86_64 GNU/Linux | | whoami | Current username | username | | id | User and group IDs | uid=1000(user) gid=1000(user) | | w | Logged-in users | Shows users and their activities | | last | Login history | Recent login records |
Log File Monitoring
#### Common Log Locations
`bash
/var/log/syslog # System messages
/var/log/auth.log # Authentication logs
/var/log/kern.log # Kernel messages
/var/log/apache2/access.log # Apache access logs
/var/log/mysql/error.log # MySQL error logs
`
#### Log Monitoring Commands
`bash
tail -f /var/log/syslog # Follow system log
journalctl -f # Follow systemd journal
journalctl -u service_name # Show logs for specific service
dmesg # Kernel ring buffer messages
`
Network Commands
Network troubleshooting and configuration commands are essential for system connectivity management.
Network Connectivity Testing
#### ping (Network Connectivity Test)
`bash
ping google.com # Test connectivity to host
ping -c 4 google.com # Send only 4 packets
ping -i 2 google.com # 2-second interval between packets
ping6 ipv6.google.com # IPv6 ping
`
#### Network Configuration
`bash
ip addr show # Show network interfaces
ip route show # Show routing table
ifconfig # Network interface configuration (legacy)
netstat -tuln # Show listening ports
ss -tuln # Modern alternative to netstat
`
Network Information Commands
| Command | Purpose | Usage Example | |---------|---------|---------------| | wget | Download files from web | wget https://example.com/file.zip | | curl | Transfer data from servers | curl -O https://example.com/file.txt | | nslookup | DNS lookup | nslookup google.com | | dig | DNS lookup (detailed) | dig google.com MX | | traceroute | Trace network path | traceroute google.com |
Firewall and Security
#### iptables (Firewall Management)
`bash
iptables -L # List firewall rules
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow SSH
iptables -A INPUT -j DROP # Default deny rule
`
#### SSH (Secure Shell)
`bash
ssh username@hostname # Connect to remote host
ssh -p 2222 username@hostname # Connect using specific port
scp file.txt username@hostname:/path/ # Copy file to remote host
rsync -av local/ username@hostname:remote/ # Synchronize directories
`
File Permissions and Ownership
Linux file permissions control access to files and directories, forming a crucial security mechanism.
Understanding Permissions
#### Permission Types - r (read): View file contents or list directory contents - w (write): Modify file contents or create/delete files in directory - x (execute): Run file as program or enter directory
#### Permission Categories - Owner (u): File owner permissions - Group (g): Group member permissions - Others (o): All other users permissions
Permission Representation
#### Symbolic Notation
`
-rwxr-xr--
│││││││││
│└┴┴─ others permissions (r--)
│ └┴┴─ group permissions (r-x)
│ └┴┴─ owner permissions (rwx)
└─ file type (- for regular file, d for directory)
`
#### Numeric (Octal) Notation
| Permission | Binary | Octal | |------------|--------|-------| | --- | 000 | 0 | | --x | 001 | 1 | | -w- | 010 | 2 | | -wx | 011 | 3 | | r-- | 100 | 4 | | r-x | 101 | 5 | | rw- | 110 | 6 | | rwx | 111 | 7 |
Permission Management Commands
#### chmod (Change Mode)
`bash
chmod 755 filename # Set permissions using octal
chmod u+x filename # Add execute for owner
chmod g-w filename # Remove write for group
chmod o=r filename # Set others to read-only
chmod -R 644 directory/ # Recursive permission change
`
Common Permission Combinations: - 644: rw-r--r-- (files) - 755: rwxr-xr-x (directories and executables) - 600: rw------- (private files) - 700: rwx------ (private directories)
#### chown (Change Ownership)
`bash
chown username filename # Change owner
chown username:groupname filename # Change owner and group
chown :groupname filename # Change group only
chown -R username:group directory/ # Recursive ownership change
`
#### chgrp (Change Group)
`bash
chgrp groupname filename # Change group ownership
chgrp -R groupname directory/ # Recursive group change
`
Package Management
Package management systems handle software installation, updates, and removal across different Linux distributions.
Debian/Ubuntu (APT)
#### Basic APT Commands
`bash
apt update # Update package lists
apt upgrade # Upgrade installed packages
apt install package_name # Install package
apt remove package_name # Remove package
apt purge package_name # Remove package and configuration
apt search keyword # Search for packages
apt show package_name # Show package information
`
#### Advanced APT Operations
`bash
apt list --installed # List installed packages
apt list --upgradable # List upgradable packages
apt autoremove # Remove unnecessary packages
apt autoclean # Clean package cache
dpkg -i package.deb # Install local deb package
dpkg -l # List installed packages
`
Red Hat/CentOS (YUM/DNF)
#### YUM Commands
`bash
yum update # Update all packages
yum install package_name # Install package
yum remove package_name # Remove package
yum search keyword # Search packages
yum info package_name # Package information
yum list installed # List installed packages
`
#### DNF Commands (Modern replacement for YUM)
`bash
dnf update # Update packages
dnf install package_name # Install package
dnf remove package_name # Remove package
dnf search keyword # Search packages
dnf history # Show transaction history
`
Package Management Comparison
| Distribution | Package Manager | Package Format | Configuration | |--------------|----------------|----------------|---------------| | Ubuntu/Debian | APT | .deb | /etc/apt/ | | Red Hat/CentOS | YUM/DNF | .rpm | /etc/yum.repos.d/ | | Arch Linux | Pacman | .pkg.tar.xz | /etc/pacman.conf | | SUSE | Zypper | .rpm | /etc/zypp/ |
Advanced Commands and Concepts
Text Editors
#### vim (Vi Improved)
`bash
vim filename # Open file in vim
`
Basic vim Commands: - i: Insert mode - Esc: Command mode - :w: Save file - :q: Quit - :wq: Save and quit - :q!: Quit without saving - dd: Delete line - yy: Copy line - p: Paste
#### nano (Simple Text Editor)
`bash
nano filename # Open file in nano
`
nano Key Shortcuts: - Ctrl+O: Save file - Ctrl+X: Exit - Ctrl+K: Cut line - Ctrl+U: Paste line - Ctrl+W: Search
Archive and Compression
#### tar (Tape Archive)
`bash
tar -cvf archive.tar files/ # Create tar archive
tar -czvf archive.tar.gz files/ # Create compressed archive
tar -xvf archive.tar # Extract tar archive
tar -xzvf archive.tar.gz # Extract compressed archive
tar -tvf archive.tar # List archive contents
`
tar Options: - c: Create archive - x: Extract archive - v: Verbose output - f: Specify filename - z: Gzip compression - j: Bzip2 compression
#### Compression Tools
`bash
gzip filename # Compress file
gunzip filename.gz # Decompress file
zip archive.zip files/ # Create zip archive
unzip archive.zip # Extract zip archive
`
System Services
#### systemctl (SystemD Service Control)
`bash
systemctl status service_name # Check service status
systemctl start service_name # Start service
systemctl stop service_name # Stop service
systemctl restart service_name # Restart service
systemctl enable service_name # Enable service at boot
systemctl disable service_name # Disable service at boot
systemctl list-units # List all units
`
Environment Variables
#### Managing Environment Variables
`bash
env # List all environment variables
echo $PATH # Display PATH variable
export VARIABLE_NAME=value # Set environment variable
unset VARIABLE_NAME # Remove environment variable
`
Important Environment Variables: - PATH: Executable search paths - HOME: User home directory - USER: Current username - SHELL: Current shell program - PWD: Present working directory
Daily Practice Routine
Week 1: Foundation Building
#### Day 1-2: Navigation Mastery
`bash
Practice these commands daily
pwd # Always know where you are cd /var/log && ls -la # Navigate and explore cd ~ && find . -name "*.txt" | head -5 # Find files in home directory`#### Day 3-4: File Operations
`bash
Daily file manipulation practice
mkdir -p practice/day{1..7} # Create practice directories touch practice/day1/file{1..5}.txt # Create multiple files cp -r practice/day1 practice/backup # Practice copying`#### Day 5-7: Text Processing
`bash
Daily text processing exercises
ps aux | grep $USER # Filter processes ls -la | sort -k5 -n # Sort by file size cat /etc/passwd | cut -d: -f1 | sort # Extract and sort usernames`Week 2: Intermediate Skills
#### Daily System Monitoring
`bash
Morning system check routine
uptime && free -h && df -h # System status overview ps aux --sort=-%cpu | head -10 # Top CPU processes tail -20 /var/log/syslog # Recent system messages`#### Permission Practice
`bash
Daily permission exercises
find ~/practice -type f -exec chmod 644 {} \; # Set file permissions find ~/practice -type d -exec chmod 755 {} \; # Set directory permissions ls -la ~/practice/ # Verify permissions`Week 3: Advanced Operations
#### Automation Scripts
`bash
#!/bin/bash
Daily backup script example
DATE=$(date +%Y%m%d) tar -czf backup_$DATE.tar.gz ~/important_files/ find ~/backups/ -name "backup_*.tar.gz" -mtime +7 -delete`#### Log Analysis
`bash
Daily log analysis routine
grep "ERROR" /var/log/syslog | tail -10 # Recent errors awk '{print $1}' /var/log/auth.log | sort | uniq -c | sort -nr | head -5`Week 4: Integration and Mastery
#### Complex Command Combinations
`bash
Advanced daily exercises
find /var/log -name "*.log" -mtime -1 -exec grep -l "error" {} \; ps aux | awk '{sum+=$3} END {print "Total CPU:", sum"%"}' netstat -tuln | awk '/LISTEN/ {print $4}' | sort`Monthly Assessment Checklist
#### Core Competencies Verification
| Skill Area | Assessment Task | Proficiency Level | |------------|----------------|-------------------| | Navigation | Navigate entire file system without assistance | Beginner/Intermediate/Advanced | | File Operations | Create, copy, move, delete files efficiently | Beginner/Intermediate/Advanced | | Text Processing | Use grep, sed, awk for data manipulation | Beginner/Intermediate/Advanced | | Process Management | Monitor and control system processes | Beginner/Intermediate/Advanced | | Permissions | Understand and modify file permissions | Beginner/Intermediate/Advanced | | System Monitoring | Interpret system performance metrics | Beginner/Intermediate/Advanced |
Best Practices for Daily Practice
#### Consistency Guidelines 1. Daily Commitment: Practice for at least 30 minutes daily 2. Progressive Learning: Build upon previous day's knowledge 3. Real-world Application: Use commands for actual tasks 4. Documentation: Keep notes of useful command combinations 5. Experimentation: Try variations of commands safely
#### Safety Considerations 1. Backup Important Data: Always backup before experimenting 2. Use Test Environments: Practice destructive commands safely 3. Understand Before Executing: Read command documentation 4. Verify Permissions: Check file permissions before modification 5. Monitor System Resources: Avoid overwhelming system resources
#### Learning Resources
- Man Pages: Use man command_name for detailed documentation
- Info Pages: Use info command_name for comprehensive guides
- Online Documentation: Refer to distribution-specific documentation
- Practice Environments: Use virtual machines for safe experimentation
- Community Forums: Engage with Linux communities for problem-solving
This comprehensive guide provides the foundation for mastering Linux basics through structured daily practice. Regular application of these commands and concepts will develop proficiency in Linux system administration and command-line operations. Remember that mastery comes through consistent practice and real-world application of these fundamental skills.