🐧💻
Linux Commands & Shell Basics
Complete Reference Guide
Structured for Learning • Commands • Examples
From Beginner to Professional
📋 Table of Contents
6. Viewing File Contents .......... 8
Fundamentals
Advanced Features
1. Getting Help & Documentation ..... 3
7. Shell Features & Commands ....... 9
2. Understanding the File System ..... 4
8. Special Files & Devices ........ 10
3. Basic Navigation ................ 5
Quick Reference
Core Operations
9. Essential Command Cheat Sheet .... 11
4. Working with Files ............. 6
10. Troubleshooting & Tips ......... 12
5. Working with Directories ........ 7
11. Glossary ....................... 13
1 Getting Help & Documentation
🎯 Start Here: Before using any command, learn how to get help. This is your most
important skill in Linux!
📖 Man Pages - Your Primary Reference
man <command> – View manual page for a command
man -k <keyword> – Search manual entries by keyword
man <section> <command> – View specific section (e.g., man 5 passwd )
apropos <keyword> – Same as man -k
whatis <command> – One-line description of command
man hier – Understand filesystem hierarchy
🔢 Man Page Sections
Section Content Example
1 User commands man 1 ls
5 File formats man 5 passwd
8 System admin commands man 8 mount
🔍 Finding Commands & Information
which <command> – Find location of executable
whereis <command> – Find binary, source, and man page
type <command> – Show how command would be interpreted
help <builtin> – Help for shell built-in commands
info <command> – GNU info documents (more detailed than man)
⌨️ Navigating Man Pages
Key Action
Space Next page
b Previous page
/text Search for "text"
n Next search result
q Quit
# Example: Get help workflow man ls # Read the manual ls --help # Quick usage summary
which ls # Find where ls is located type ls # Check if it's built-in or external
2 Understanding the File System
🧠 Core Concept: In Linux, "Everything is a File" - directories, devices, processes are
all represented as files.
🗂️ Linux Directory Structure (FHS - Filesystem Hierarchy
Standard)
Directory Purpose Examples
/ Root - top of filesystem Starting point for all paths
/bin Essential user binaries ls, cat, cp, mv, rm
/sbin System administration binaries mount, reboot, ifconfig
/usr/bin User programs Most application binaries
/usr/sbin Non-essential system binaries Network daemons, services
/etc Configuration files /etc/passwd, /etc/hosts
/home User home directories /home/username
/root Root user's home Separate from /home
/tmp Temporary files Cleared on reboot
/var Variable data Logs, mail, print spools
/var/log System log files System and application logs
/dev Device files Hardware interfaces
/proc Process & kernel info Virtual filesystem
/sys System information Hardware information
🔗 Path Types
Absolute Paths Relative Paths
Start with / (root) Relative to current directory
documents/file.txt ../parent-directory/
/home/user/documents/file.txt ./current-directory/
/etc/passwd /var/log/messages
📁 Special Directory Symbols
. – Current directory
.. – Parent directory
~ – Home directory
- – Previous directory (with cd)
💡 Memory Aid: /bin = basic commands everyone uses, /sbin = system/super-user
commands
3 Basic Navigation
🧭 Essential Navigation Commands
pwd – Print Working Directory (where am I?)
cd <directory> – Change Directory
ls – List directory contents
📂 Change Directory (cd) Options
Command Action Example
cd Go to home directory Same as cd ~
cd ~ Go to home directory Explicit home reference
cd .. Go up one level To parent directory
cd - Go to previous directory Toggle between two locations
cd / Go to root directory Top of filesystem
cd ../../ Go up two levels Navigate to parent's parent
📋 List Directory Contents (ls) Options
ls – Basic file listing
ls -l – Long format (detailed info)
ls -a – Show all files (including hidden)
ls -la – Detailed listing including hidden files
ls -lh – Human-readable file sizes
ls -lt – Sort by modification time
ls -lr – Reverse sort order
ls -R – Recursive listing (show subdirectories)
🔍 Understanding ls -l Output
-rw-r--r-- 1 user group 1024 Mar 15 10:30 filename.txt | | | | | | | | | | | | | └─
filename | | | | | └─ modification date/time | | | | └─ file size in bytes | | | └─
group owner | | └─ user owner | └─ number of hard links └─ file permissions
⌨️ Navigation Shortcuts
Tab – Auto-complete paths and filenames
Tab Tab – Show all possible completions
Ctrl+L – Clear screen
history – Show command history
!! – Repeat last command
# Navigation example workflow pwd # Check current location ls -la # See what's here cd
documents/ # Go to documents folder pwd # Confirm location cd .. # Go back up cd - #
Return to documents
🚀 Pro Tip: Use Tab completion religiously - it prevents typos and speeds up navigation
significantly!
4 Working with Files
⚠️ Important: Linux is case-sensitive ! File.txt and file.txt are different files.
📄 File Creation
touch <filename> – Create empty file or update timestamp
touch file1 file2 file3 – Create multiple files
touch -t YYYYMMDDhhmm <file> – Set specific timestamp
📝 Creating Files with Content
# Method 1: Using cat cat > newfile.txt Type your content here Press Ctrl+D to save #
Method 2: Using echo echo "Hello World" > newfile.txt # Method 3: Using cat with here
document cat > newfile.txt << END Multiple lines of content END
🔍 File Information
file <filename> – Identify file type (ignores extension)
file * – Check all files in directory
file -s <device> – Check special files in /dev
stat <filename> – Detailed file information
📋 File Copying
cp <source> <destination> – Copy file
cp -i <source> <dest> – Interactive (confirm overwrites)
cp -r <dir> <dest> – Copy directories recursively
cp -p <source> <dest> – Preserve timestamps/permissions
cp *.txt backup/ – Copy all .txt files
🔄 File Moving/Renaming
mv <old> <new> – Move or rename file
mv -i <old> <new> – Interactive mode
mv file1 file2 dir/ – Move multiple files to directory
🗑️ File Deletion
rm <filename> – Remove file permanently
rm -i <filename> – Interactive deletion (confirm)
rm -f <filename> – Force deletion (no prompts)
rm *.tmp – Delete all .tmp files
🚨 Danger Zone: There's no "recycle bin" in Linux command line. Deleted files are gone
forever! Always use -i flag when learning.
🔄 Bulk File Operations
# Rename multiple files (Ubuntu/Debian) rename 's/.txt/.bak/' *.txt # Rename multiple
files (RHEL/CentOS) rename .txt .bak *.txt # Copy all .conf files to backup directory
cp *.conf backup/ # Move all log files to archive mv *.log archive/
💡 Best Practice: Always test with ls first to see what files match your pattern before
running destructive operations.
5 Working with Directories
🏗️ Directory Creation
mkdir <dirname> – Create single directory
mkdir dir1 dir2 dir3 – Create multiple directories
mkdir -p path/to/nested/dir – Create nested directories
mkdir -m 755 dirname – Create with specific permissions
🗑️ Directory Removal
rmdir <dirname> – Remove empty directory
rmdir -p nested/empty/dirs – Remove nested empty directories
rm -r <dirname> – Remove directory and contents
rm -rf <dirname> – Force remove (dangerous!)
rm -ri <dirname> – Interactive recursive removal
🚨 Extreme Caution: rm -rf will delete everything without confirmation. Double-check
your path!
📂 Directory Copying
cp -r <source_dir> <dest_dir> – Copy directory recursively
cp -rp <source> <dest> – Copy preserving attributes
cp -ri <source> <dest> – Interactive recursive copy
🔄 Directory Moving
mv <old_dir> <new_dir> – Rename directory
mv <dir> <parent_dir>/ – Move directory to new location
mv -i <dir> <dest> – Interactive move
📊 Directory Analysis
ls -la <dirname> – List directory contents in detail
ls -R <dirname> – Recursive listing
du -h <dirname> – Directory size (human readable)
du -sh <dirname> – Summary of directory size
find <dirname> -type f | wc -l – Count files in directory
🎯 Common Directory Patterns
# Create project structure mkdir -p project/{src,docs,tests,config} # Safe directory
removal ls -la dirname/ # Check contents first rm -ri dirname/ # Remove interactively #
Copy directory structure only (no files) find source/ -type d -exec mkdir -p dest/{} \;
# Backup directory with timestamp cp -r important_dir important_dir.backup.$(date
+%Y%m%d)
💡 Pro Tip: Use mkdir -p to create entire directory paths in one command - it won't fail
if directories already exist.
6 Viewing File Contents
📜 Complete File Display
cat <filename> – Display entire file
cat file1 file2 – Display multiple files
cat -n <filename> – Display with line numbers
tac <filename> – Display file in reverse (last line first)
📄 Paginated Viewing
less <filename> – View file page by page (recommended)
more <filename> – Basic page-by-page viewer
Less Navigation Commands
Key Action
Space Next page
b Previous page
/pattern Search forward
?pattern Search backward
n Next search result
N Previous search result
G Go to end of file
1G Go to beginning
q Quit
👁️ Partial File Viewing
Head (Beginning of File) Tail (End of File)
head <file> – First 10 lines tail <file> – Last 10 lines
head -n 20 <file> – First 20 lines tail -n 20 <file> – Last 20 lines
head -c 100 <file> – First 100 bytes tail -f <file> – Follow file updates
head -n -5 <file> – All except last 5 tail -n +5 <file> – From line 5 to end
lines
📊 Real-time File Monitoring
tail -f <logfile> – Follow file updates in real-time
tail -F <logfile> – Follow file, handle rotation
watch cat <file> – Refresh file display every 2 seconds
watch -n 1 tail <file> – Watch file updates every second
🔧 Specialized Content Commands
strings <binary_file> – Extract readable text from binary
hexdump -C <file> – View file in hexadecimal format
od -c <file> – View file showing special characters
🎯 Practical Examples
# Monitor system log in real-time tail -f /var/log/syslog # View configuration file
safely less /etc/passwd # Check last 50 lines of log file tail -n 50 /var/log/messages
# View first 20 lines with line numbers head -n 20 script.sh | cat -n # Follow multiple
log files tail -f /var/log/apache2/*.log
📊 Log Analysis: Use tail -f to monitor log files during troubleshooting - it's essential
for system administration!
7 Shell Features & Commands
💬 Echo Command
echo "text" – Display text
echo -n "text" – No trailing newline
echo -e "text\twith\ttabs" – Enable escape sequences
echo $HOME – Display environment variable
🔤 Quoting and Escaping
Single Quotes Double Quotes
'literal text' # Preserves everything "allows variables" # Allows variable
exactly echo 'The $HOME directory' # expansion echo "The $HOME directory" #
Output: The $HOME directory Output: The /home/user directory
🔧 Control Operators
Operator Function Example
; Command separator ls; pwd; date
& Background process long_command &
&& Run if previous succeeds make && make install
|| Run if previous fails test -f file || touch file
# Comment # This is a comment
long_command \
\ Line continuation
--with-options
🧩 Command Types
type <command> – Show command type (builtin/external/alias)
which <command> – Find external command location
command -v <cmd> – Portable way to find command
Built-in vs External Commands
Built-in Commands External Commands
Part of the shell itself: Separate programs:
cd ls
echo cat
pwd grep
help find
🔗 Aliases
alias name='command' – Create alias
alias – List all aliases
unalias name – Remove alias
\command – Run command bypassing alias
# Useful aliases alias ll='ls -la' alias la='ls -A' alias l='ls -CF' alias ..='cd ..'
alias grep='grep --color=auto'
🧠 Exit Status and Debugging
$? – Exit status of last command (0 = success)
set -x – Show command expansion (debug mode)
set +x – Turn off debug mode
history – Show command history
!! – Repeat last command
# Testing command success ls /nonexistent echo $? # Shows non-zero (failure) ls /home
echo $? # Shows 0 (success) # Conditional execution based on success test -f myfile.txt
&& echo "File exists" || echo "File missing"
🔍 Debugging: Use set -x to see exactly how the shell expands your commands -
great for learning!
8 Special Files & Devices
🔌 Important Device Files (/dev)
Device File Purpose Common Use
/dev/null Data black hole command > /dev/null
/dev/zero Source of null bytes Create files of specific size
/dev/random True random numbers Cryptographic applications
/dev/urandom Pseudo-random numbers General random data
/dev/sda1 First partition of first disk Storage device access
/dev/tty Current terminal Direct terminal access
🗂️ Virtual Filesystems
/proc Directory /sys Directory
Process and kernel information: Hardware and kernel parameters:
/proc/cpuinfo – CPU details /sys/class/ – Device classes
/proc/meminfo – Memory info /sys/block/ – Block devices
/proc/version – Kernel version /sys/devices/ – Device tree
/proc/[PID]/ – Process info
📚 Additional Important Directories
Directory Purpose Key Contents
/lib Essential shared libraries Libraries for /bin and /sbin
/usr/lib Non-essential libraries Application libraries
/boot Boot loader files Kernel, initrd, GRUB config
/etc/init.d/ Service control scripts Start/stop daemon scripts
/var/cache Application cache data Package manager cache
/var/spool Queued data Mail, print jobs, cron
/opt Optional software Third-party applications
🎯 Practical Uses of Special Files
# Discard command output noisy_command > /dev/null 2>&1 # Create a file of specific
size (1MB) dd if=/dev/zero of=testfile bs=1M count=1 # Generate random password tr -dc
A-Za-z0-9 < /dev/urandom | head -c 12 # Check system information cat /proc/cpuinfo cat
/proc/meminfo cat /proc/version # Check current terminal tty echo "Hello" > /dev/tty
🔒 Security Note: Use /dev/urandom for most random data needs. /dev/random can
block waiting for entropy.
💡 System Info: The /proc filesystem is your window into system status - great for
monitoring and troubleshooting!
9 Essential Command Cheat Sheet
🚀 Must-Know Commands 📁 Directory Operations
# Navigation pwd # Where am I? ls -la # # Directory Management mkdir dir #
Show all files cd ~ # Go home cd - # Create directory mkdir -p path/dir #
Previous directory # Help & Information Create nested dirs rmdir dir # Remove
man command # Manual page which command empty dir rm -r dir # Remove with
# Find executable type command # contents cp -r dir newdir # Copy
Command type file filename # File type directory # Content Viewing head file #
# Basic File Operations touch file # First 10 lines tail file # Last 10
Create empty file cat file # Display lines tail -f file # Follow changes
file cp file newfile # Copy file mv less file # Page through file cat -n
file newname # Move/rename rm file # file # With line numbers
Delete file
⚡ Power User Shortcuts
# Keyboard Shortcuts Tab # Auto-complete Ctrl+C # Cancel command Ctrl+D # End
input/logout Ctrl+L # Clear screen !! # Last command # File Operations with
Confirmation cp -i source dest # Copy with prompt mv -i old new # Move with prompt rm -
i file # Delete with prompt # Quick File Creation echo "content" > file # Create file
with content cat > file # Type content, Ctrl+D to save cat >> file # Append to file #
System Information df -h # Disk space du -sh directory # Directory size ps aux #
Running processes top # System monitor
🎯 Common Patterns
# Safe Operations ls -la directory/ # Check before operations test -f file && echo
"exists" # Test file existence command1 && command2 # Run command2 if command1 succeeds
command1 || echo "failed" # Show message if command1 fails # Backup Patterns cp
important.txt important.txt.backup mkdir backup.$(date +%Y%m%d) tar -czf backup.tar.gz
directory/ # Log Monitoring tail -f /var/log/syslog # Follow system log tail -n 100
logfile # Last 100 lines grep "ERROR" logfile # Find errors
📊 File Listing Formats
# Understanding ls -l output: # -rw-r--r-- 1 user group 1024 Mar 15 10:30 filename #
||||||||| | | | | | | # ||||||||| | | | | | └─ filename # ||||||||| | | | | └─
date/time modified # ||||||||| | | | └─ size in bytes # ||||||||| | | └─ group owner #
||||||||| | └─ user owner # ||||||||| └─ number of links # └─────────── permissions
(user/group/other)
🏆 Exam Success: Practice these commands until they're automatic. Focus on the
patterns and logical combinations!
10 Troubleshooting & Tips
🚨 Common Mistakes to Avoid:
Forgetting Linux is case-sensitive
Using rm -rf without double-checking paths
Not using Tab completion (leads to typos)
Forgetting to check current directory with pwd
🔧 Problem-Solving Workflow
1. Understand the problem: What are you trying to do?
2. Check current state: pwd , ls -la
3. Verify command syntax: man command
4. Test safely: Use echo to preview, -i flags
5. Check results: echo $? for exit status
🎯 Best Practices
Always use Tab completion - prevents typos and speeds you up
Check before destructive operations: Use ls to verify what you're affecting
Use interactive flags when learning: -i with cp, mv, rm
Read error messages carefully - they usually tell you exactly what's wrong
Practice regularly - muscle memory is crucial for exams
🔍 When Commands Don't Work
# Command not found? which commandname # Is it installed? echo $PATH # Is it in PATH?
type commandname # Check command type # Permission denied? ls -la filename # Check file
permissions pwd # Am I in the right directory? id # Check my user/group # File not
found? ls -la # Is the file really there? pwd # Am I in the right directory? file
filename # What type of file is it?
📚 Quick Reference for Errors
Error Message Common Cause Solution
command not found Typo or not installed Check spelling, use which
Permission denied No read/write/execute access Check with ls -la
No such file or directory Wrong path or filename Check pwd , use Tab completion
Directory not empty Trying to rmdir non-empty dir Use rm -r or empty first
File exists Trying to create existing file Use different name or -f flag
🧠 Memory Aids
pwd: "Print Working Directory" - where am I?
ls: "List" - what's here?
cd: "Change Directory" - go somewhere
man: "Manual" - how do I use this?
cat: "Concatenate" - show me the content
less is more: less is better than more for viewing files
⌨️ Essential Keyboard Shortcuts
Shortcut Action When to Use
Tab Auto-complete Always! Prevents typos
Ctrl+C Cancel command Stop running process
Ctrl+D End input Exit cat input, logout
Ctrl+L Clear screen Clean up terminal
q Quit Exit less, more, man pages
🏆 Exam Strategy: Stay calm, read questions carefully, and remember that Tab
completion is your friend. Practice these commands until they're second nature!
11 Glossary
FHS (Filesystem Hierarchy Standard):
Absolute Path: Complete file path starting from Standard that defines the directory structure and
root directory (/). Example: organization of Unix-like systems
/home/user/documents/file.txt
Hidden Files: Files whose names start with a dot
Alias: A shortcut name for a command. Created
(.). Shown with ls -a
with alias name='command'
Interactive Mode: Commands that prompt for
Built-in Command: Command that's part of the user confirmation before acting (using -i flag)
shell itself (like cd, echo, pwd)
Man Pages: Manual pages providing detailed
Device File: Special file in /dev that represents documentation for commands and system
hardware devices or kernel interfaces components
External Command: Separate program with its
own binary file (like ls, cat, grep)