Learn Linux in 2 Weeks.pdf
Learn Linux in 2 Weeks.pdf
LINUX IN 2 WEEKS
Presented by
DEVOPS DIARIES
Presented by
Avinash Tietler
TABLE OF CONTENTS
1. Introduction To Linux
2. File Management
3. User Management
4. Networking
5. Process Management
6. Text Editor
7. Shell Scripting
8. Package Management
14. Troubleshooting
1. INTRODUCTION TO LINUX
What is Linux?
History and Distributions
Linux Architecture Overview
Applications
Shell
Kernel
Hardware
Kernel: At its core, Linux is a kernel, which is the heart of the OS. It
manages system resources and hardware communication.
History of Linux
Unix Inspiration (1969): Unix was developed at Bell Labs as a multi-
user, multitasking operating system.
Modern Era:
Linux powers 90% of cloud infrastructure, 100% of the top 500
supercomputers, and the Android operating system.
➣ Arch-based:
Arch Linux: Minimalist and highly customizable, for advanced users.
Manjaro: Beginner-friendly Arch-based distro with pre-configured
settings.
What is Linux?
History and Distributions
Linux Architecture Overview
➣ Others:
OpenSUSE: Stable and user-friendly, ideal for developers.
Kali Linux: Specialized for penetration testing and ethical hacking.
Alpine Linux: Lightweight and security-focused for containers.
Kernel
The Linux kernel is the core component of the OS, responsible for
managing system resources and hardware communication.
What is Linux?
History and Distributions
Linux Architecture Overview
Key Functions:
1. Process Management: Manages process creation, scheduling, and
termination.
2. Memory Management: Allocates and deallocates memory for
processes and handles virtual memory.
3. Device Drivers: Interfaces with hardware devices like disks,
keyboards, and printers.
4. File System Management: Provides access to and organizes data
in files and directories.
5. Networking: Handles communication between systems over a
network.
Shell
The shell acts as an interface between the user and the kernel.
It interprets user commands and forwards them to the kernel for
execution.
Types of Shells:
1. Bash (Bourne Again Shell): The most common and user-friendly
shell.
2. Zsh (Z Shell): Extended functionality with improved scripting.
3. C Shell (csh): Syntax similar to the C programming language.
4. Korn Shell (ksh): Combines features of the C and Bourne shells.
System Libraries
Libraries provide reusable code for common functionalities like file
handling, memory management, or GUI operations.
GNU C Library (glibc) is an essential library in Linux.
What is Linux?
History and Distributions
Linux Architecture Overview
System Utilities
These are user-level tools and utilities that allow users to perform
tasks like file management, text editing, and process monitoring.
Examples:
ls (list files and directories)
cp (copy files)
ps (process status)
2. FILE MANAGEMENT
File System Hierarchy in Linux
File Operations (cp, mv, rm, touch, cat)
Understanding File Permissions (chmod, chown)
Hidden Files and Directories
Key Directories:
/ (Root): The top of the file system. All files and directories are under
this.
/bin: Essential user binaries (commands like ls, cp, mv).
/boot: Boot-related files (e.g., the kernel and bootloader
configurations).
/dev: Device files (e.g., sda for disks).
/etc: System configuration files.
/home: Home directories for users (e.g., /home/user).
/lib: Shared libraries and kernel modules.
/opt: Optional software packages.
/tmp: Temporary files.
/usr: User utilities and applications (e.g., /usr/bin, /usr/lib).
/var: Variable files like logs, databases, and cache.
File System Hierarchy in Linux
File Operations (cp, mv, rm, touch, cat)
Understanding File Permissions (chmod, chown)
Hidden Files and Directories
Create Directories:
mkdir dirname: Creates a new directory.
mkdir -p parent/child: Creates parent and child directories.
View Files:
cat file: Displays file content.
less file: Displays file content one screen at a time.
head file: Shows the first 10 lines.
tail file: Shows the last 10 lines.
Move/Rename Files:
mv source destination: Moves/renames a file.
Example: mv file1 /tmp/ (move to /tmp) or mv oldname newname.
Copy Files:
cp source destination: Copies a file.
Example: cp file1 /tmp/.
Format:
Example: -rwxr-xr--
First character: File type (- for files, d for directories).
Next three characters: Owner permissions (rwx).
Next three characters: Group permissions (r-x).
Last three characters: Others permissions (r — ).
Modify Permissions:
chmod 755 file: Sets permissions using octal values.
7: Read + Write + Execute.
5: Read + Execute.
chmod u+x file: Adds execute permission for the owner (u = user, g =
group, o = others).
Change Ownership:
chown user:group file: Changes owner and group.
Example: chown alice:developers file.txt.
3. USER MANAGEMENT
Understanding User and Groups
Adding, Modifying, and Deleting Users
Switching Users (su, sudo)
Managing Group Permissions
Types of users:
✅ Root User: Superuser with unrestricted access.
✅ Regular Users: Have limited permissions.
✅ System Users: Created for running services.
Modifying a User
sudo usermod -l newname oldname → Rename a user
sudo usermod -aG groupname username → Add user to a group
Deleting a User
sudo userdel username → Delete user but keep files
sudo userdel -r username → Delete user and remove home directory
Understanding User and Groups
Adding, Modifying, and Deleting Users
Switching Users (su, sudo)
Managing Group Permissions
🎯 Key Takeaways:
✅ Use useradd, usermod, userdel for user management.
✅ Switch users with su and sudo.
✅ Manage access with groups and permissions.
✅ Regularly audit user accounts for security.
4. NETWORKING BASICS
Understanding IP Configuration (ifconfig, ip addr)
Managing Network Interfaces
Checking Connectivity (ping, traceroute)
Basics of SSH and Remote Login
IP Configuration
IP configuration is essential for network communication. In Linux, you
can configure and view IP addresses, subnet masks, gateways, and DNS
settings.
Key Concepts:
IP Address: A unique identifier for a device on a network (e.g.,
192.168.1.10).
Subnet Mask: Defines the network portion of the IP address (e.g.,
255.255.255.0).
Gateway: The IP address of the router that connects your network
to other networks (e.g., 192.168.1.1).
DNS: Translates domain names (e.g., google.com) to IP addresses.
Understanding IP Configuration (ifconfig, ip addr)
Managing Network Interfaces
Checking Connectivity (ping, traceroute)
Basics of SSH and Remote Login
➲ Persistent Configuration:
Edit the network configuration file (depends on the Linux distribution):
Debian/Ubuntu: /etc/network/interfaces
Red Hat/CentOS: /etc/sysconfig/network-scripts/ifcfg-eth0
Systemd-based systems: Use netplan (e.g., /etc/netplan/01-
netcfg.yaml).
Understanding IP Configuration (ifconfig, ip addr)
Managing Network Interfaces
Checking Connectivity (ping, traceroute)
Basics of SSH and Remote Login
➲ Checking Connectivity
To troubleshoot network issues, you can use tools like ping and
traceroute.
SSH Basics:
1. Connect to a Remote Server:
ssh username@remote_host
ssh user@192.168.1.100
2. Specify a Port (default is 22):
ssh -p 2222 user@192.168.1.100
3. Copy Files with SCP:
scp file.txt user@192.168.1.100:/path/to/destination
4. Generate SSH Keys (for passwordless login):
ssh-keygen -t rsa -b 4096
5. Copy the public key to the remote server:
ssh-copy-id user@192.168.1.100
ps (Process Status)
The ps command displays a snapshot of currently running
processes.
It does not update dynamically like top or htop.
ps aux # Shows all running processes with details
ps -ef # Alternative format for displaying all processes
ps -u <username> # Shows processes for a specific user
ps -p <PID> # Displays information about a specific process
Summary
Viewing Processes: Use ps, top, or htop to monitor processes.
Managing Processes: Use kill, pkill, nice, and renice to control
processes.
Background/Foreground Processes: Use &, fg, bg, and Ctrl+Z to
manage process execution states.
6. LINUX TEXT EDITORS
Basics of vi/vim
nano and other common editors
Editing, saving, and quitting files
Vi/Vim
Vi is a classic, screen-oriented text editor originally created for Unix.
Vim (Vi Improved) is an enhanced version of Vi, with additional
features like syntax highlighting, plugins, and better user interface
options.
Vim is pre-installed on most Linux distributions and is widely used
for editing configuration files, writing code, and scripting.
Nano
Simple and beginner-friendly.
Easy-to-use interface with on-screen shortcuts.
Ideal for quick edits and beginners.
Emacs
Highly customizable and extensible.
More than just a text editor — it’s an ecosystem for coding, email,
and more.
Requires time to learn but offers unmatched flexibility.
Basics of vi/vim
nano and other common editors
Editing, saving, and quitting files
Shell scripting is one of the most powerful tools in a Linux user’s arsenal.
Whether you’re a system administrator, developer, or just a curious
Linux enthusiast, learning shell scripting can save you time and effort by
automating repetitive tasks.
In this post, we’ll cover the basics of shell scripting, from writing your
first script to using variables, loops, and conditionals. Let’s dive in!
#!/bin/bash is called the shebang. It tells the system to use the Bash
shell to execute the script.
echo is a command that prints text to the terminal.
Save the file and exit the editor (in Nano, press Ctrl+O to save and
Ctrl+X to exit).
Make the script executable: chmod +x hello.sh
Run the script: ./hello.sh
You should see the output: Hello, World!
What is Shell Scripting?
Writing Your First Script
Variables, Loops, and Conditionals
Simple Automation with Shell Scripts
Variables
Variables are used to store data. In shell scripting, you can create a
variable and use it later in your script.
#!/bin/bash
name=”Avinash”
echo “Hello, $name!”
Output: Hello, $name!
Variables are assigned using = (no spaces around the =).
To access a variable’s value, use $ followed by the variable name.
Loops
Loops allow you to repeat a set of commands. The most common loop in
shell scripting is the for loop.
#!/bin/bash
for i in 1 2 3 4
do
echo “Number: $i”
done
Conditionals
Conditionals allow you to execute commands based on certain conditions.
The most common conditional is the if statement.
#!/bin/bash
age=18
if [ $age -ge 18 ]; then
What is Shell Scripting?
Writing Your First Script
Variables, Loops, and Conditionals
Simple Automation with Shell Scripts
# Create a timestamp
timestamp=$(date +”%Y%m%d_%H%M%S”)
# Create backup
tar -czf $backup_dest/backup_$timestamp.tar.gz $backup_dir
echo “Backup completed: backup_$timestamp.tar.gz”
Installing Software
To install software using a package manager, you typically use a
command like:
APT (Debian/Ubuntu): sudo apt install package_name
DNF (Fedora): sudo dnf install package_name
Pacman (Arch): sudo pacman -S package_name
Installing and Managing Software (apt, yum, dnf, zypper)
Working with Snap and Flatpak
Updating and Removing Software
Snap
Developed by Canonical (the company behind Ubuntu).
Packages are called snaps.
Managed by the snapd service.
Installing Snap: sudo apt install snapd
Installing Software with Snap: sudo snap install package_name
Updating Snap Packages: sudo snap refresh package_name
Removing Snap Packages: sudo snap remove package_name
Flatpak
A community-driven universal package format.
Packages are hosted in repositories called remotes.
Managed by the flatpak command.
Installing Flatpak: sudo apt install flatpak
Installing and Managing Software (apt, yum, dnf, zypper)
Working with Snap and Flatpak
Updating and Removing Software
Removing Software
To remove software, use the appropriate command for your package
manager.
APT: sudo apt remove package_name # Removes the package
sudo apt purge package_name # Removes the package and its
configuration files
Summary
Package Managers are essential tools for installing, updating, and
removing software in Linux.
Snap and Flatpak provide universal packaging solutions, making it easier
to distribute and run software across different Linux distributions.
Regular updates ensure your system is secure and up to date.
Properly removing software and cleaning up unused packages helps
maintain system performance.
9. SYSTEM PERFORMANCE AND TUNING
System monitoring and performance tuning in Linux are critical tasks for
ensuring that a system runs efficiently and reliably. These tasks involve
tracking system resources, identifying bottlenecks, and optimizing
performance. Below is a detailed explanation of the key components,
including disk usage and monitoring, memory and CPU monitoring, and
analyzing system logs.
Tools:
journalctl (Systemd Journal):
Queries and displays logs managed by the systemd journal.
Example: journalctl -xe (view recent logs with extended details).
Filters: journalctl -u service_name (logs for a specific service), journalctl --
since "2023-10-01" --until "2023-10-02" (logs within a time range).
Performance Tuning
Performance tuning involves optimizing system parameters to improve
efficiency. Common areas for tuning include:
Disk I/O: Use tools like ionice to adjust I/O priority.
Optimize filesystem mount options (e.g., noatime for ext4).
Advanced Permissions
Linux uses a combination of traditional file permissions and advanced
mechanisms like ACLs, SUID, and SGID to provide fine-grained access
control.
Commands:
setfacl: Sets ACLs for files or directories.
setfacl -m u:username:rwx file.txt (grants read, write, and execute
permissions to a specific user).
getfacl: Displays ACLs for a file or directory.
getfacl file.txt.
Use Case: Useful when you need to grant permissions to multiple users
or groups beyond the standard owner/group/others.
Setting Advanced Permissions (ACLs, SUID, SGID)
Using Firewalls (ufw, iptables)
Basics of SELinux and AppArmor
How to Set:
chmod u+s file (sets SUID bit).
Example: chmod u+s /usr/bin/passwd (allows users to change their
passwords by running the passwd command with root privileges).
Security Consideration: Use SUID sparingly, as it can introduce security
risks if misconfigured.
How to Set:
chmod g+s directory (sets SGID bit).
Example: chmod g+s /shared_directory (ensures all files in
/shared_directory belong to the same group).
Use Case: Useful for collaborative environments where multiple users
need to share files.
Setting Advanced Permissions (ACLs, SUID, SGID)
Using Firewalls (ufw, iptables)
Basics of SELinux and AppArmor
Using Firewalls
Firewalls are essential for controlling incoming and outgoing network
traffic. Linux provides tools like ufw and iptables to configure firewall
rules.
iptables:
What it is: A powerful command-line tool for configuring firewall rules.
Commands:
Allow traffic: sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
(allow SSH).
Block traffic: sudo iptables -A INPUT -p tcp --dport 80 -j DROP
(block HTTP).
List rules: sudo iptables -L.
Use Case: Suitable for advanced users who need granular control over
network traffic.
Setting Advanced Permissions (ACLs, SUID, SGID)
Using Firewalls (ufw, iptables)
Basics of SELinux and AppArmor
Commands:
Check status: sestatus.
Change mode: sudo setenforce Enforcing or sudo setenforce
Permissive.
View context: ls -Z (files), ps -Z (processes).
Use Case: Commonly used in enterprise environments for enhanced
security.
Setting Advanced Permissions (ACLs, SUID, SGID)
Using Firewalls (ufw, iptables)
Basics of SELinux and AppArmor
AppArmor:
A security module that confines programs to a limited set of resources
using profiles.
Key Concepts:
Profiles: Each application has a profile defining its allowed actions
and resources.
Modes: Enforce (restricts access), Complain (logs violations but
does not restrict).
Commands:
Check status: sudo apparmor_status.
Load/unload profiles: sudo apparmor_parser -r
/etc/apparmor.d/profile_name.
Use Case: Easier to configure than SELinux and often used in Ubuntu
and other distributions.
Summary
Advanced Permissions: Use ACLs, SUID, and SGID for fine-grained
access control.
Firewalls: Use ufw for simplicity or iptables for advanced
configurations.
SELinux and AppArmor: Implement mandatory access control to
enforce security policies.
11. ADVANCED SHELL SCRIPTING
Here are the key areas to focus on for advanced shell scripting:
a. Advanced Variable Manipulation
Parameter Expansion: Learn ${variable#pattern},
${variable%pattern}, ${variable//pattern/replacement}, etc.
Arrays: Work with indexed and associative arrays.
Environment Variables: Understand how to set and use them
effectively.
b. Functions
Writing reusable functions.
Passing arguments to functions.
Returning values from functions.
Local vs global variables.
c. Input/Output Redirection
Advanced redirection (>, >>, 2>, &>, <<, etc.).
Using exec to redirect input/output for the entire script.
Process substitution (<(command) and >(command)).
Writing Complex Scripts
Using Functions and Arrays
Scheduling with Cron Jobs
d. Regular Expressions
Using grep, sed, and awk with regex.
Pattern matching in shell scripts.
e. Advanced Control Structures
Nested loops and conditionals.
Using case statements for complex decision-making.
select for creating menus.
f. Error Handling
Checking exit codes ($?).
Using trap to handle signals and errors.
Logging and debugging techniques.
g. Process Management
Running commands in the background (&).
Using wait to synchronize processes.
Job control (jobs, fg, bg).
Killing processes (kill, pkill).
h. Text Processing
Advanced usage of awk and sed.
Parsing CSV, JSON, and XML files (using tools like jq for
JSON).
Working with multi-line text.
i. File and Directory Manipulation
Recursive directory traversal.
Handling file permissions and ownership.
Using find with -exec or xargs.
Writing Complex Scripts
Using Functions and Arrays
Scheduling with Cron Jobs
j. Networking
Writing scripts to interact with network utilities (curl, wget, nc,
ssh, etc.).
Automating network tasks (e.g., checking connectivity,
downloading files).
k. Script Optimization
Writing efficient scripts.
Avoiding common pitfalls (e.g, excessive use of external
commands).
Using shell built-ins whenever possible.
l. Security
Writing secure scripts (e.g., avoiding code injection).
Handling sensitive data (e.g., passwords, API keys).
Using set -e, set -u, and set -o pipefail for safer scripts.
Key Points:
Use set -e to exit the script immediately if any command fails.
Use trap to handle unexpected errors or interruptions.
Log all actions for debugging and auditing purposes.
Writing Complex Scripts
Using Functions and Arrays
Scheduling with Cron Jobs
Key Points:
Use local to limit the scope of variables within functions.
Pass arrays to functions using "${array[@]}".
Functions can return values using echo or by modifying global
variables.
Service:
Start a service: sudo service <service-name> start
Stop a service: sudo service <service-name> stop
Restart a service: sudo service <service-name> restart
Check the status of a service: sudo service <service-name>
status
The init system is the first process that starts when a Linux system
boots. It is responsible for starting and managing other services
and daemons.
Starting, Stopping, and Managing Services (systemctl, service)
Configuring Startup Services
Understanding Init Systems (SysVinit vs. systemd)
SysVinit
The traditional init system used in older Linux distributions.
Uses scripts located in /etc/init.d/ to manage services.
Services are started sequentially, which can lead to slower
boot times.
Managed using commands like service and chkconfig.
systemd
The modern init system used in most Linux distributions today
(e.g., Ubuntu, Fedora, CentOS 7+).
Uses units (.service files) located in /etc/systemd/system/ or
/lib/systemd/system/.
Starts services in parallel, leading to faster boot times.
Managed using the systemctl command.
13. LINUX IN CLOUD AND DEVOPS
Linux in DevOps
Most DevOps Tools Run on Linux: Tools like Docker, Kubernetes,
Jenkins, Terraform, Ansible, and Prometheus are designed for
Linux environments.
Scripting and Automation: Shell scripting (Bash, Zsh) and
automation tools work seamlessly in Linux, enabling DevOps
engineers to automate tasks efficiently.
Containerization & Microservices: Docker containers, Kubernetes
clusters, and CI/CD pipelines are primarily deployed on Linux-
based servers.
Infrastructure as Code (IaC): Terraform and Ansible use Linux-
friendly configurations to manage cloud infrastructure efficiently.
Troubleshooting Tips:
GRUB Issues: Use a live CD/USB to chroot into the system and
reinstall GRUB.
Kernel Panics: Check kernel logs (dmesg) and ensure hardware
compatibility.
Init System Failures: Use journalctl (for systemd) or check
/var/log/messages for errors.
Troubleshooting Tips:
Resource Usage: Use top or htop to identify resource-hogging
processes.
Network Issues: Use ping and traceroute to diagnose connectivity
problems.
Package Issues: Use dpkg -l or rpm -qa to verify installed packages.
Troubleshooting Tips:
Log Rotation: Use logrotate to manage log file sizes.
Real-time Monitoring: Use tail -f /var/log/syslog to monitor logs in
real-time.
Log Analysis: Use grep, awk, and sed to filter and analyze logs.
Troubleshooting Tips:
Disk Space: Use df -h to check disk usage and du -sh * to find large
files.
Filesystem Corruption: Use fsck to check and repair filesystems.
Mount Issues: Check /etc/fstab for errors and use dmesg to identify
mount failures.
Troubleshooting Tips:
Connectivity: Use ping and traceroute to diagnose network issues.
DNS Issues: Check /etc/resolv.conf and use nslookup or dig to test
DNS resolution.
Firewall Rules: Use iptables -L or ufw status to verify firewall rules.
Troubleshooting Tips:
Service Failures: Use systemctl status <service> to check service
status and logs.
Process Issues: Use ps aux | grep <process> to find and manage
processes.
Resource Limits: Use ulimit to check and set resource limits.
Troubleshooting Tips:
Permission Issues: Use ls -l to check file permissions and ownership.
SELinux/AppArmor: Use audit2allow to analyze and fix SELinux denials.
User Access: Check /etc/passwd, /etc/shadow, and /etc/group for
user and group information.
Troubleshooting Tips:
Backup Verification: Regularly verify backups to ensure they are
complete and usable.
Recovery Planning: Have a documented recovery plan and test it
periodically.
Debugging Common Linux Issues
Working with Network Tools
Troubleshooting Tips:
Script Debugging: Use set -x in Bash scripts for debugging.
Cron Jobs: Check /var/log/cron.log for cron job errors.