Full Stack • Java • System Design • Cloud • AI Engineering

Linux2026-06-07

Linux Basic Commands: Complete Guide for Developers

Master essential Linux commands for navigation, file management, permissions, process management, networking, and troubleshooting with real-world examples and best practices.

Linux Basic Commands: Complete Guide for Developers


📋 Table of Contents

  1. What are Linux Commands?
  2. Why Do We Need Linux Commands?
  3. Real-World Use Cases
  4. Syntax
  5. Internal Working
  6. Memory Diagram
  7. Data Flow Diagram
  8. Code Examples
  9. Common Mistakes
  10. Performance Considerations
  11. Interview Questions
  12. Cheat Sheet
  13. Summary

1. What are Linux Commands?

Linux commands are text-based instructions that interact with the Linux operating system through a shell (terminal). They allow you to perform operations like file management, process control, networking, and system administration.

Linux Command Structure

┌─────────────────────────────────────────────────────────────┐
│         LINUX COMMAND ANATOMY                                │
└─────────────────────────────────────────────────────────────┘

command [options] [arguments]
   ↓        ↓          ↓
Program   Flags    Input/Output

Example:
ls -la /home/user
│   │   │
│   │   └─ Argument (path)
│   └───── Options (long format, all files)
└───────── Command (list)

Components:
───────────
• Command: The program to execute
• Options: Modify command behavior (-, --)
• Arguments: Input data (files, directories, text)

Linux Filesystem Hierarchy

┌─────────────────────────────────────────────────────────────┐
│         LINUX FILESYSTEM STRUCTURE                           │
└─────────────────────────────────────────────────────────────┘

/                           Root directory
├── bin/                    Essential binaries (ls, cp, mv)
├── boot/                   Boot loader files
├── dev/                    Device files
├── etc/                    Configuration files
├── home/                   User home directories
│   └── username/           Individual user directory
├── lib/                    System libraries
├── media/                  Removable media mount points
├── mnt/                    Temporary mount points
├── opt/                    Optional software
├── proc/                   Process information
├── root/                   Root user home
├── sbin/                   System binaries
├── srv/                    Service data
├── sys/                    System information
├── tmp/                    Temporary files
├── usr/                    User programs
│   ├── bin/                User binaries
│   ├── lib/                User libraries
│   └── local/              Locally installed software
└── var/                    Variable data
    ├── log/                Log files
    ├── mail/               Mail
    └── tmp/                Temporary files

Key Concepts:
─────────────
• Everything is a file (including devices)
• Case-sensitive filesystem
• Forward slashes (/) for paths
• Hidden files start with dot (.)
• No drive letters (C:, D:)

2. Why Do We Need Linux Commands?

The Problem Linux Commands Solve

┌─────────────────────────────────────────────────────────────┐
│         WITHOUT LINUX COMMANDS                               │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  GUI-Only Limitations:                                       │
│  ────────────────────                                       │
│  • Slow for repetitive tasks                                │
│  • Cannot automate                                          │
│  • Limited remote access                                    │
│  • Resource intensive                                       │
│  • Not scriptable                                           │
│  • Difficult to troubleshoot servers                        │
│                                                              │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│         WITH LINUX COMMANDS                                  │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Command-Line Benefits:                                      │
│  ──────────────────────                                     │
│  ✓ Fast and efficient                                       │
│  ✓ Fully automatable                                        │
│  ✓ Remote access via SSH                                    │
│  ✓ Lightweight (no GUI needed)                              │
│  ✓ Scriptable and repeatable                                │
│  ✓ Essential for servers                                    │
│  ✓ DevOps and CI/CD integration                             │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Why Linux Dominates

Linux powers:

  • 96.3% of top 1 million web servers
  • 100% of top 500 supercomputers
  • All major cloud platforms (AWS, Azure, GCP)
  • Docker containers
  • Kubernetes clusters
  • Android devices
  • IoT devices

3. Real-World Use Cases

1. DevOps and CI/CD

# Deploy application
ssh user@server
cd /opt/app
git pull origin main
./build.sh
systemctl restart app
tail -f /var/log/app.log

2. Server Management

# Monitor server health
top                    # CPU and memory
df -h                  # Disk usage
netstat -tulpn         # Network connections
journalctl -xe         # System logs

3. Docker and Kubernetes

# Container management
docker ps -a
docker logs container_id
kubectl get pods
kubectl describe pod pod_name

4. Log Analysis

# Find errors in logs
grep "ERROR" /var/log/app.log
grep -r "Exception" /var/log/
tail -f /var/log/syslog | grep "failed"

5. Automation Scripts

# Backup script
#!/bin/bash
tar -czf backup-$(date +%Y%m%d).tar.gz /data
aws s3 cp backup-*.tar.gz s3://backups/
find . -name "backup-*.tar.gz" -mtime +7 -delete

6. Performance Troubleshooting

# Identify performance issues
ps aux --sort=-%mem | head
iostat -x 1
vmstat 1
sar -u 1 10

4. Syntax

Navigation Commands

# ═══════════════════════════════════════════════════════════
# NAVIGATION
# ═══════════════════════════════════════════════════════════

# Print working directory
pwd
# Output: /home/user/projects

# List files
ls                     # Basic list
ls -l                  # Long format
ls -la                 # Include hidden files
ls -lh                 # Human-readable sizes
ls -lt                 # Sort by time
ls -lS                 # Sort by size

# Change directory
cd /path/to/directory  # Absolute path
cd Documents           # Relative path
cd ..                  # Parent directory
cd ~                   # Home directory
cd -                   # Previous directory

File Management Commands

# ═══════════════════════════════════════════════════════════
# FILE OPERATIONS
# ═══════════════════════════════════════════════════════════

# Create files
touch file.txt
touch file1.txt file2.txt file3.txt

# Create directories
mkdir directory
mkdir -p parent/child/grandchild  # Create nested

# Copy files
cp source.txt destination.txt
cp -r source_dir dest_dir         # Recursive (directories)
cp -v source.txt dest.txt         # Verbose
cp -i source.txt dest.txt         # Interactive (prompt)

# Move/Rename files
mv old_name.txt new_name.txt      # Rename
mv file.txt /path/to/directory/   # Move
mv *.txt Documents/               # Move multiple

# Delete files
rm file.txt
rm -r directory                   # Recursive
rm -rf directory                  # Force recursive (⚠️ dangerous)
rm -i file.txt                    # Interactive

# View file contents
cat file.txt                      # Entire file
less file.txt                     # Paginated view
more file.txt                     # Paginated (older)
head file.txt                     # First 10 lines
head -n 20 file.txt               # First 20 lines
tail file.txt                     # Last 10 lines
tail -n 20 file.txt               # Last 20 lines
tail -f file.txt                  # Follow (real-time)

Search Commands

# ═══════════════════════════════════════════════════════════
# SEARCH
# ═══════════════════════════════════════════════════════════

# Find files
find . -name "*.java"             # By name
find . -type f -name "*.log"      # Files only
find . -type d -name "config"     # Directories only
find . -mtime -7                  # Modified in last 7 days
find . -size +100M                # Larger than 100MB
find . -name "*.tmp" -delete      # Find and delete

# Search content in files
grep "ERROR" app.log              # Basic search
grep -i "error" app.log           # Case-insensitive
grep -r "TODO" .                  # Recursive
grep -n "ERROR" app.log           # Show line numbers
grep -v "INFO" app.log            # Invert match (exclude)
grep -c "ERROR" app.log           # Count matches
grep -A 5 "ERROR" app.log         # 5 lines after match
grep -B 5 "ERROR" app.log         # 5 lines before match
grep -C 5 "ERROR" app.log         # 5 lines around match

Permission Commands

# ═══════════════════════════════════════════════════════════
# PERMISSIONS
# ═══════════════════════════════════════════════════════════

# View permissions
ls -l file.txt
# Output: -rwxr-xr-x 1 user group 1234 Jan 1 12:00 file.txt
#         │││││││││
#         │││││││└─ Others execute
#         ││││││└── Others write
#         │││││└─── Others read
#         ││││└──── Group execute
#         │││└───── Group write
#         ││└────── Group read
#         │└─────── Owner execute
#         └──────── Owner write/read

# Change permissions (numeric)
chmod 755 script.sh               # rwxr-xr-x
chmod 644 file.txt                # rw-r--r--
chmod 600 private.key             # rw-------
chmod 777 file.txt                # rwxrwxrwx (⚠️ avoid)

# Change permissions (symbolic)
chmod +x script.sh                # Add execute
chmod -w file.txt                 # Remove write
chmod u+x script.sh               # User execute
chmod g+w file.txt                # Group write
chmod o-r file.txt                # Others no read

# Change ownership
chown user file.txt               # Change owner
chown user:group file.txt         # Change owner and group
chown -R user directory           # Recursive

Process Management

# ═══════════════════════════════════════════════════════════
# PROCESSES
# ═══════════════════════════════════════════════════════════

# List processes
ps                                # Current shell processes
ps aux                            # All processes
ps -ef                            # Full format
ps aux | grep java                # Find Java processes

# Real-time monitoring
top                               # Interactive process viewer
htop                              # Enhanced top (if installed)
top -u username                   # User's processes

# Kill processes
kill PID                          # Graceful termination
kill -9 PID                       # Force kill
killall process_name              # Kill by name
pkill -f "java.*MyApp"            # Kill by pattern

# Background processes
command &                         # Run in background
jobs                              # List background jobs
fg %1                             # Bring job 1 to foreground
bg %1                             # Resume job 1 in background
nohup command &                   # Run immune to hangups

5. Internal Working

How Linux Commands Execute

┌─────────────────────────────────────────────────────────────┐
│         COMMAND EXECUTION FLOW                               │
└─────────────────────────────────────────────────────────────┘

User Input: ls -la /home
     ↓
┌─────────────────────────────────────────┐
│  1. Shell (bash/zsh)                     │
│     • Parses command                     │
│     • Expands wildcards                  │
│     • Resolves variables                 │
└─────────────────────────────────────────┘
     ↓
┌─────────────────────────────────────────┐
│  2. PATH Resolution                      │
│     • Searches /bin, /usr/bin, etc.     │
│     • Finds executable                   │
└─────────────────────────────────────────┘
     ↓
┌─────────────────────────────────────────┐
│  3. Fork Process                         │
│     • Creates child process              │
│     • Copies parent environment          │
└─────────────────────────────────────────┘
     ↓
┌─────────────────────────────────────────┐
│  4. Execute Binary                       │
│     • Loads program into memory          │
│     • Passes arguments                   │
└─────────────────────────────────────────┘
     ↓
┌─────────────────────────────────────────┐
│  5. System Calls                         │
│     • Interacts with kernel              │
│     • Accesses filesystem                │
│     • Manages resources                  │
└─────────────────────────────────────────┘
     ↓
┌─────────────────────────────────────────┐
│  6. Return Output                        │
│     • STDOUT (standard output)           │
│     • STDERR (error output)              │
│     • Exit code (0 = success)            │
└─────────────────────────────────────────┘
     ↓
Display to User

Shell Types

┌─────────────────────────────────────────────────────────────┐
│         POPULAR SHELLS                                       │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Bash (Bourne Again Shell)                                  │
│  ──────────────────────────                                 │
│  • Most common                                              │
│  • Default on most Linux distributions                      │
│  • Rich scripting capabilities                              │
│                                                              │
│  Zsh (Z Shell)                                               │
│  ─────────────                                              │
│  • Enhanced features                                        │
│  • Better auto-completion                                   │
│  • Themes and plugins (Oh My Zsh)                           │
│                                                              │
│  Fish (Friendly Interactive Shell)                           │
│  ──────────────────────────────────                         │
│  • User-friendly                                            │
│  • Syntax highlighting                                      │
│  • Auto-suggestions                                         │
│                                                              │
│  Sh (Bourne Shell)                                           │
│  ─────────────────                                          │
│  • Original Unix shell                                      │
│  • Minimal features                                         │
│  • POSIX compliant                                          │
│                                                              │
└─────────────────────────────────────────────────────────────┘

6. Memory Diagram

┌─────────────────────────────────────────────────────────────┐
│         LINUX PROCESS MEMORY LAYOUT                          │
└─────────────────────────────────────────────────────────────┘

High Memory Address (0xFFFFFFFF)
┌──────────────────────────────────────┐
│  Kernel Space                         │
│  (Protected, not accessible)          │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│  Stack                                │
│  • Local variables                    │
│  • Function parameters                │
│  • Return addresses                   │
│  • Grows downward ↓                   │
└──────────────────────────────────────┘
         ↓ (grows down)
         
         ↑ (grows up)
┌──────────────────────────────────────┐
│  Heap                                 │
│  • Dynamic memory allocation          │
│  • malloc(), new                      │
│  • Grows upward ↑                     │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│  BSS Segment                          │
│  • Uninitialized global variables    │
│  • Static variables                   │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│  Data Segment                         │
│  • Initialized global variables       │
│  • Static variables                   │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│  Text Segment (Code)                  │
│  • Program instructions               │
│  • Read-only                          │
└──────────────────────────────────────┘
Low Memory Address (0x00000000)

Example: ls command execution
──────────────────────────────
Stack:
  • argc, argv (command arguments)
  • Local variables in functions
  
Heap:
  • Directory listing data
  • File information structures
  
Data:
  • Global configuration
  • Static buffers
  
Text:
  • ls program code
  • Library functions

7. Data Flow Diagram

┌─────────────────────────────────────────────────────────────┐
│         LINUX I/O STREAMS                                    │
└─────────────────────────────────────────────────────────────┘

┌──────────────┐
│   Keyboard   │ ──→ STDIN (0)
└──────────────┘         ↓
                         ↓
                  ┌──────────────┐
                  │   Command    │
                  │   Process    │
                  └──────────────┘
                         ↓
                    ┌────┴────┐
                    ↓         ↓
              STDOUT (1)  STDERR (2)
                    ↓         ↓
              ┌─────────┐ ┌─────────┐
              │ Screen  │ │ Screen  │
              └─────────┘ └─────────┘

Redirection Examples:
─────────────────────

# Redirect STDOUT to file
command > output.txt

# Redirect STDERR to file
command 2> error.txt

# Redirect both
command > output.txt 2>&1

# Append to file
command >> output.txt

# Redirect STDIN from file
command < input.txt

# Pipe output to another command
command1 | command2

# Pipe chain
cat file.txt | grep "ERROR" | wc -l

Pipeline Flow

┌─────────────────────────────────────────────────────────────┐
│         COMMAND PIPELINE                                     │
└─────────────────────────────────────────────────────────────┘

ps aux | grep java | awk '{print $2}' | xargs kill

┌────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
│ ps aux │ →  │   grep   │ →  │   awk    │ →  │  xargs   │
│        │    │   java   │    │ print $2 │    │   kill   │
└────────┘    └──────────┘    └──────────┘    └──────────┘
    ↓              ↓               ↓               ↓
All processes  Filter Java   Extract PID    Kill process

Flow:
─────
1. ps aux: List all processes
2. grep java: Filter lines containing "java"
3. awk '{print $2}': Extract 2nd column (PID)
4. xargs kill: Pass PIDs to kill command

8. Code Examples

Example 1: File Management Script

#!/bin/bash
# Organize files by extension

# Create directories
mkdir -p Documents Images Videos Archives

# Move files
mv *.txt *.doc *.pdf Documents/
mv *.jpg *.png *.gif Images/
mv *.mp4 *.avi *.mkv Videos/
mv *.zip *.tar *.gz Archives/

echo "Files organized successfully!"

Example 2: System Monitoring

#!/bin/bash
# Monitor system resources

echo "=== System Health Check ==="
echo ""

# CPU Usage
echo "CPU Usage:"
top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1

# Memory Usage
echo ""
echo "Memory Usage:"
free -h | grep Mem | awk '{print $3 "/" $2}'

# Disk Usage
echo ""
echo "Disk Usage:"
df -h | grep "^/dev" | awk '{print $1 ": " $5}'

# Top 5 processes by memory
echo ""
echo "Top 5 Memory Consumers:"
ps aux --sort=-%mem | head -6 | tail -5 | awk '{print $11 ": " $4 "%"}'

Example 3: Log Analysis

#!/bin/bash
# Analyze application logs

LOG_FILE="/var/log/app.log"

echo "=== Log Analysis ==="
echo ""

# Count errors
ERROR_COUNT=$(grep -c "ERROR" $LOG_FILE)
echo "Total Errors: $ERROR_COUNT"

# Count warnings
WARN_COUNT=$(grep -c "WARN" $LOG_FILE)
echo "Total Warnings: $WARN_COUNT"

# Find unique error messages
echo ""
echo "Unique Errors:"
grep "ERROR" $LOG_FILE | awk -F'ERROR' '{print $2}' | sort | uniq -c | sort -rn | head -10

# Errors in last hour
echo ""
echo "Errors in last hour:"
grep "ERROR" $LOG_FILE | grep "$(date -d '1 hour ago' '+%Y-%m-%d %H')" | wc -l

Example 4: Backup Script

#!/bin/bash
# Automated backup script

SOURCE_DIR="/home/user/projects"
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backup_$DATE.tar.gz"

# Create backup
echo "Creating backup..."
tar -czf $BACKUP_DIR/$BACKUP_FILE $SOURCE_DIR

# Check if successful
if [ $? -eq 0 ]; then
    echo "Backup created: $BACKUP_FILE"
    
    # Delete backups older than 7 days
    find $BACKUP_DIR -name "backup_*.tar.gz" -mtime +7 -delete
    echo "Old backups cleaned up"
else
    echo "Backup failed!"
    exit 1
fi

Example 5: Process Management

#!/bin/bash
# Manage Java application

APP_NAME="MyApp"
JAR_FILE="app.jar"
PID_FILE="/var/run/myapp.pid"

start() {
    if [ -f $PID_FILE ]; then
        echo "Application already running"
        exit 1
    fi
    
    echo "Starting $APP_NAME..."
    nohup java -jar $JAR_FILE > /dev/null 2>&1 &
    echo $! > $PID_FILE
    echo "Started with PID: $(cat $PID_FILE)"
}

stop() {
    if [ ! -f $PID_FILE ]; then
        echo "Application not running"
        exit 1
    fi
    
    PID=$(cat $PID_FILE)
    echo "Stopping $APP_NAME (PID: $PID)..."
    kill $PID
    rm $PID_FILE
    echo "Stopped"
}

status() {
    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null; then
            echo "$APP_NAME is running (PID: $PID)"
        else
            echo "$APP_NAME is not running (stale PID file)"
        fi
    else
        echo "$APP_NAME is not running"
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 2
        start
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac

9. Common Mistakes

Mistake 1: Using rm -rf Without Verification

# ❌ Dangerous: Can delete everything
rm -rf /

# ❌ Wrong: Typo can be catastrophic
rm -rf / home/user/temp  # Space after / deletes root!

# ✅ Correct: Always verify path
ls /home/user/temp
rm -rf /home/user/temp

# ✅ Better: Use interactive mode
rm -ri /home/user/temp

Mistake 2: Not Checking Command Success

# ❌ Wrong: Doesn't check if cd succeeded
cd /nonexistent/directory
rm -rf *  # Deletes files in current directory!

# ✅ Correct: Check exit status
cd /target/directory || exit 1
rm -rf *

# ✅ Better: Use set -e in scripts
#!/bin/bash
set -e  # Exit on any error
cd /target/directory
rm -rf *

Mistake 3: Incorrect Permissions

# ❌ Wrong: Too permissive
chmod 777 file.txt  # Everyone can read/write/execute

# ✅ Correct: Appropriate permissions
chmod 644 file.txt  # Owner: rw, Others: r
chmod 600 private.key  # Owner only: rw

# ❌ Wrong: Making everything executable
chmod +x *

# ✅ Correct: Only scripts
chmod +x *.sh

Mistake 4: Not Quoting Variables

# ❌ Wrong: Breaks with spaces
FILE="my file.txt"
rm $FILE  # Tries to delete "my" and "file.txt"

# ✅ Correct: Quote variables
rm "$FILE"

# ❌ Wrong: Word splitting
for file in $(ls *.txt); do
    echo $file
done

# ✅ Correct: Use arrays or proper quoting
for file in *.txt; do
    echo "$file"
done

Mistake 5: Ignoring Exit Codes

# ❌ Wrong: Doesn't check if command succeeded
grep "ERROR" app.log
echo "Found errors"

# ✅ Correct: Check exit code
if grep -q "ERROR" app.log; then
    echo "Found errors"
else
    echo "No errors found"
fi

# ✅ Better: Store and check
grep "ERROR" app.log
if [ $? -eq 0 ]; then
    echo "Found errors"
fi

10. Performance Considerations

1. Efficient File Searching

# ❌ Slow: Searches entire filesystem
find / -name "file.txt"

# ✅ Fast: Limit search scope
find /home/user -name "file.txt"

# ✅ Faster: Use locate (if available)
locate file.txt

# ✅ Fastest: Use specific paths
ls /home/user/projects/file.txt

2. Optimize Grep Operations

# ❌ Slow: Searches all files
grep -r "pattern" /

# ✅ Fast: Limit file types
grep -r --include="*.log" "pattern" /var/log

# ✅ Faster: Use fixed strings
grep -F "exact string" file.txt  # No regex

# ✅ Fastest: Stop after first match
grep -m 1 "pattern" file.txt

3. Efficient Piping

# ❌ Slow: Multiple passes
cat file.txt | grep "ERROR" | grep "CRITICAL"

# ✅ Fast: Single grep with pattern
grep "ERROR.*CRITICAL" file.txt

# ❌ Slow: Unnecessary cat
cat file.txt | grep "pattern"

# ✅ Fast: Direct grep
grep "pattern" file.txt

4. Batch Operations

# ❌ Slow: Loop with individual commands
for file in *.txt; do
    cp "$file" /backup/
done

# ✅ Fast: Single command
cp *.txt /backup/

# ❌ Slow: Multiple find executions
find . -name "*.log" -exec rm {} \;

# ✅ Fast: Batch with +
find . -name "*.log" -exec rm {} +

5. Resource Monitoring

# Monitor command resource usage
time command              # Execution time
/usr/bin/time -v command  # Detailed stats

# Limit resources
ulimit -t 60              # CPU time limit (seconds)
ulimit -v 1000000         # Virtual memory limit (KB)
nice -n 19 command        # Lower priority
ionice -c 3 command       # Idle I/O priority

11. Interview Questions

Q1: What is the difference between absolute and relative paths?

Answer:

  • Absolute path: Starts from root directory (/). Example: /home/user/file.txt
  • Relative path: Starts from current directory. Example: Documents/file.txt
# Absolute path (always works from anywhere)
cd /home/user/projects

# Relative path (depends on current location)
cd projects  # Only works if you're in /home/user

Q2: How do you find and kill a process?

Answer:

# Method 1: Using ps and grep
ps aux | grep java
kill PID

# Method 2: Using pgrep
pgrep -f "java.*MyApp"
kill $(pgrep -f "java.*MyApp")

# Method 3: Using pkill
pkill -f "java.*MyApp"

# Force kill
kill -9 PID

Q3: Explain file permissions (rwx)

Answer:

-rwxr-xr-x
│││││││││
│││││││└─ Others: execute
││││││└── Others: write (-)
│││││└─── Others: read
││││└──── Group: execute
│││└───── Group: write (-)
││└────── Group: read
│└─────── Owner: execute
└──────── Owner: write & read

Numeric representation:
r = 4, w = 2, x = 1
rwx = 7, r-x = 5, r-- = 4
chmod 755 = rwxr-xr-x

Q4: How do you monitor logs in real-time?

Answer:

# Follow log file
tail -f /var/log/app.log

# Follow with grep filter
tail -f /var/log/app.log | grep "ERROR"

# Multiple files
tail -f /var/log/*.log

# With line numbers
tail -fn 100 /var/log/app.log

# Using journalctl (systemd)
journalctl -f -u service_name

Q5: What is the difference between > and >>?

Answer:

  • > : Overwrites file (truncates existing content)
  • >> : Appends to file (preserves existing content)
# Overwrite
echo "New content" > file.txt

# Append
echo "Additional content" >> file.txt

# Redirect STDERR
command 2> error.log

# Redirect both STDOUT and STDERR
command > output.log 2>&1

Q6: How do you find files modified in the last 24 hours?

Answer:

# Modified in last 24 hours
find . -mtime -1

# Modified in last 7 days
find . -mtime -7

# Modified more than 30 days ago
find . -mtime +30

# Accessed in last hour
find . -amin -60

# Changed in last 10 minutes
find . -cmin -10

Q7: How do you check disk usage?

Answer:

# Overall disk usage
df -h

# Directory size
du -sh /path/to/directory

# Top 10 largest directories
du -h /path | sort -rh | head -10

# Specific filesystem
df -h /dev/sda1

# Inode usage
df -i

Q8: What is the difference between soft link and hard link?

Answer:

Feature Soft Link (Symbolic) Hard Link
Command ln -s target link ln target link
Points to File path Inode
Cross filesystem Yes No
Works if original deleted No Yes
Directory linking Yes No (usually)
# Create soft link
ln -s /path/to/file link_name

# Create hard link
ln /path/to/file link_name

# View links
ls -l  # Shows -> for soft links

12. Cheat Sheet

Quick Reference

# ═══════════════════════════════════════════════════════════
# NAVIGATION
# ═══════════════════════════════════════════════════════════
pwd                    # Print working directory
ls -la                 # List all files (detailed)
cd /path               # Change directory
cd ~                   # Go home
cd -                   # Previous directory

# ═══════════════════════════════════════════════════════════
# FILE OPERATIONS
# ═══════════════════════════════════════════════════════════
touch file.txt         # Create file
mkdir dir              # Create directory
cp src dest            # Copy
mv src dest            # Move/rename
rm file                # Delete file
rm -rf dir             # Delete directory (⚠️)

# ═══════════════════════════════════════════════════════════
# VIEWING FILES
# ═══════════════════════════════════════════════════════════
cat file.txt           # Display file
less file.txt          # Paginated view
head -n 20 file.txt    # First 20 lines
tail -f file.txt       # Follow file (real-time)

# ═══════════════════════════════════════════════════════════
# SEARCH
# ═══════════════════════════════════════════════════════════
find . -name "*.log"   # Find files
grep "ERROR" file.txt  # Search in file
grep -r "pattern" .    # Recursive search

# ═══════════════════════════════════════════════════════════
# PERMISSIONS
# ═══════════════════════════════════════════════════════════
chmod 755 file         # Change permissions
chmod +x script.sh     # Make executable
chown user:group file  # Change owner

# ═══════════════════════════════════════════════════════════
# PROCESSES
# ═══════════════════════════════════════════════════════════
ps aux                 # List all processes
ps aux | grep java     # Find Java processes
top                    # Real-time monitor
kill PID               # Kill process
kill -9 PID            # Force kill

# ═══════════════════════════════════════════════════════════
# SYSTEM INFO
# ═══════════════════════════════════════════════════════════
df -h                  # Disk usage
du -sh dir             # Directory size
free -h                # Memory usage
uname -a               # System info
uptime                 # System uptime

# ═══════════════════════════════════════════════════════════
# NETWORKING
# ═══════════════════════════════════════════════════════════
ping host              # Test connectivity
curl url               # HTTP request
wget url               # Download file
netstat -tulpn         # Network connections
ss -tulpn              # Socket statistics

# ═══════════════════════════════════════════════════════════
# ARCHIVES
# ═══════════════════════════════════════════════════════════
tar -czf file.tar.gz dir   # Create tar.gz
tar -xzf file.tar.gz       # Extract tar.gz
zip -r file.zip dir        # Create zip
unzip file.zip             # Extract zip

# ═══════════════════════════════════════════════════════════
# SHORTCUTS
# ═══════════════════════════════════════════════════════════
Ctrl + C               # Stop command
Ctrl + Z               # Suspend command
Ctrl + D               # Logout
Ctrl + L               # Clear screen
Ctrl + R               # Search history
Ctrl + A               # Start of line
Ctrl + E               # End of line

Common Patterns

# Find and delete old files
find /tmp -name "*.tmp" -mtime +7 -delete

# Count lines in all log files
find . -name "*.log" -exec wc -l {} + | awk '{sum+=$1} END {print sum}'

# Find largest files
find . -type f -exec du -h {} + | sort -rh | head -10

# Monitor log for errors
tail -f /var/log/app.log | grep --line-buffered "ERROR"

# Backup with timestamp
tar -czf backup-$(date +%Y%m%d).tar.gz /data

# Kill all Java processes
pkill -9 java

# Find files containing text
grep -rl "search text" /path

# Replace text in files
find . -name "*.txt" -exec sed -i 's/old/new/g' {} +

13. Summary

Key Takeaways

Linux commands are essential for developers, DevOps, and system administrators
Command structure: command [options] [arguments]
Everything is a file in Linux (including devices)
Three I/O streams: STDIN (0), STDOUT (1), STDERR (2)
Permissions: Read (4), Write (2), Execute (1)
Process management: ps, top, kill
File operations: cp, mv, rm, find, grep
Piping and redirection: |, >, >>, <

Most Used Commands

Navigation:  pwd, ls, cd
Files:       touch, cp, mv, rm, cat, less, tail
Search:      find, grep
Permissions: chmod, chown
Processes:   ps, top, kill
System:      df, du, free
Network:     ping, curl, netstat

Best Practices

  1. Always verify paths before using rm -rf
  2. Quote variables to handle spaces
  3. Check exit codes in scripts
  4. Use appropriate permissions (avoid 777)
  5. Test commands in safe environment first
  6. Use version control for scripts
  7. Document complex commands
  8. Monitor resource usage