Kernel_shell
Chapter 4: Linux Kernel and Shell
Section titled “Chapter 4: Linux Kernel and Shell”Overview
Section titled “Overview”This chapter covers the Linux kernel architecture, kernel modules, and the shell - the primary interface for interacting with the system.
4.1 Linux Kernel Architecture
Section titled “4.1 Linux Kernel Architecture”Kernel Components
Section titled “Kernel Components”The Linux kernel is a monolithic kernel with loadable modules.
+------------------------------------------------------------------+| Linux System Architecture |+------------------------------------------------------------------+
+-----------------------+ | User Space |+-----------------------+-----------------------+--------------------+| Applications | Libraries (glibc) | Shell (bash) |+-----------------------+-----------------------+--------------------+
+-------------------------------------------------------------------+| Kernel Space |+-----------------------+-----------------------+--------------------+| System Call Interface| Kernel Subsystems | Device Drivers |+-----------------------+-----------------------+--------------------+
+-------------------------------------------------------------------+| Hardware |+-----------------------+-----------------------+--------------------+| CPU | Memory (RAM) | Disk/NIC |+-----------------------+-----------------------+--------------------+Kernel Subsystems
Section titled “Kernel Subsystems”+------------------------------------------------------------------+| Kernel Subsystems |+------------------------------------------------------------------+
+----------------+ +----------------+ +----------------+ | Process | | Memory | | File System | | Scheduler | | Manager | | (VFS) | +----------------+ +----------------+ +----------------+ | | | +----------------------+---------------------+ | +----------------+ | Network Stack | +----------------+ | +----------------+ | IPC | +----------------+
+------------------------------------------------------------------+| Subsystem | Description | Key Files |+----------------+-------------------------+-----------------------+| Process Sched | Manages CPU time | kernel/sched/* || Memory Manager| Virtual memory, paging | mm/*.c || Virtual FS | Abstraction for FS | fs/*.c || Network Stack | TCP/IP, sockets | net/*.c || IPC | Inter-process comm | ipc/*.c || Device Drivers| Hardware support | drivers/* |+----------------+-------------------------+-----------------------+4.2 Kernel Modules
Section titled “4.2 Kernel Modules”Working with Modules
Section titled “Working with Modules”# List loaded moduleslsmod
# Load a modulemodprobe module_name
# Unload a modulemodprobe -r module_name
# Show module informationmodinfo module_name
# Load module with optionsmodprobe module_name parameter=valueModule Configuration
Section titled “Module Configuration”+------------------------------------------------------------------+| Module Management |+------------------------------------------------------------------+
Load Module +--------+ Remove Module --------------> | mod | <-------------- modprobe name |probe | modprobe -r name +--------+
Module Info +--------+ | modinfo| +--------+# Blacklist a module (prevent loading)echo "blacklist module_name" > /etc/modprobe.d/blacklist.conf
# Module dependenciesdepmod -a
# View module parameterscat /sys/module/module_name/parameters/parameter_name
# Set module parameterecho value > /sys/module/module_name/parameters/parameter_name4.3 The Shell
Section titled “4.3 The Shell”Common Shells
Section titled “Common Shells”+------------------------------------------------------------------+| Shell Types |+------------------------------------------------------------------+
+----------+ +----------+ +----------+ +----------+ | bash | | zsh | | fish | | dash | +----------+ +----------+ +----------+ +----------+ | | | | v v v v Default on Power user Beginner- Fast, minimal most Linux features friendly scripts systems
+------------------------------------------------------------------+| Shell | Config File | Purpose | Best For |+----------+--------------------+-------------------+--------------+| bash | .bashrc, .bash_ | Default shell | General use || | profile | | || zsh | .zshrc | Extended features | Power users || fish | config.fish | User-friendly | Beginners || dash | (no interactive) | Fast, lightweight | Scripts |+----------+--------------------+-------------------+--------------+Starting a Shell
Section titled “Starting a Shell”# Check available shellscat /etc/shells
# Check current shellecho $SHELLecho $0
# Change shell temporarilybashzshfish
# Change default shell permanentlychsh -s /bin/zsh4.4 Shell Configuration
Section titled “4.4 Shell Configuration”Shell Configuration Files
Section titled “Shell Configuration Files”+------------------------------------------------------------------+| Shell Configuration Files |+------------------------------------------------------------------+
System-wide User-specific +-----------+ +-------------+ | /etc/ | | ~/.bash_ | | profile | | profile | +-----------+ +-------------+ | | v v +-----------+ +-------------+ | /etc/bash.| | ~/.bashrc | | bashrc | +-------------+ +-----------+ | v +-------------+ | ~/.bash_ | | history | +-------------+| File | Scope | When Loaded |
|---|---|---|
/etc/profile | System-wide | Login shells |
/etc/bash.bashrc | System-wide | Interactive bash |
~/.bash_profile | User | Login shells |
~/.bashrc | User | Interactive non-login |
~/.bash_history | User | Command history |
# Common .bashrc additionsalias ll='ls -la'alias la='ls -a'export EDITOR=vimexport PATH=$PATH:/custom/pathEnvironment Variables
Section titled “Environment Variables”+------------------------------------------------------------------+| Environment Variables Flow |+------------------------------------------------------------------+
System Default +----------+ User Override /etc/environment | export | ~/.bashrc -----------------> | VAR=val | <--------------- +----------+
+----------+ | printenv | +----------+ | v +----------+ | $VAR | +----------+# View all environment variablesenvprintenv
# View specific variableecho $HOMEprintenv HOME
# Set variable (current shell only)export VAR=value
# Set variable permanently (add to ~/.bashrc)echo 'export VAR=value' >> ~/.bashrcImportant Variables
Section titled “Important Variables”| Variable | Description |
|---|---|
HOME | User’s home directory |
PATH | Directories to search for commands |
USER | Current username |
PWD | Current working directory |
SHELL | Default shell |
EDITOR | Default text editor |
LANG | Language and locale settings |
4.5 Shell Scripting Basics
Section titled “4.5 Shell Scripting Basics”Shebang
Section titled “Shebang”#!/bin/bash#!/bin/sh#!/usr/bin/env bashVariables
Section titled “Variables”+------------------------------------------------------------------+| Variable Types |+------------------------------------------------------------------+
String Array +-------+ +-------+ | name= | | arr=( | | "John"| | one | +-------+ | two | | three | | ) | +-------+ | v +-------+ | ${arr}| +-------+# Variable assignment (no spaces around =)name="John"age=30
# Read-only variablereadonly CONSTANT="value"
# Arrayarray=(one two three)echo ${array[0]}echo ${array[@]}Control Structures
Section titled “Control Structures”+------------------------------------------------------------------+| Control Flow |+------------------------------------------------------------------+
+--------+ +--------+ +--------+ +--------+ | if |---->| elif |---->| else |---->| fi | +--------+ +--------+ +--------+ +--------+
+--------+ +--------+ +--------+ | for |---->| done |---->| esac | +--------+ +--------+ +--------+
+--------+ +--------+ +--------+ | while |---->| done |---->| esac | +--------+ +--------+ +--------+# If statementif [ condition ]; then commandelif [ condition ]; then commandelse commandfi
# Case statementcase $var in pattern1) command ;; pattern2) command ;; *) default ;;esac
# For loopfor i in {1..5}; do echo $idone
# While loopwhile read line; do echo $linedone < file.txtFunctions
Section titled “Functions”+------------------------------------------------------------------+| Function Structure |+------------------------------------------------------------------+
Function Call Function Definition +----------+ +--------------------------+ | func arg | ------------>| function_name() { | +----------+ | local arg1=$1 | | local arg2=$2 | | echo "..." | | return 0 | | } | +--------------------------+function_name() { local arg1=$1 local arg2=$2 echo "Arguments: $arg1 $arg2" return 0}
# Call functionfunction_name val1 val24.6 Input/Output
Section titled “4.6 Input/Output”Redirection
Section titled “Redirection”+------------------------------------------------------------------+| I/O Redirection |+------------------------------------------------------------------+
Standard Input (stdin) Standard Output (stdout) Standard Error (stderr) | | | v v v +-------+ +-------+ +-------+ | 0 | | 1 | | 2 | +-------+ +-------+ +-------+
Redirection Operators:
> file - Redirect stdout (overwrite) >> file - Redirect stdout (append) 2> file - Redirect stderr &> file - Redirect both < file - Redirect stdin
command > output.txt - Save output to file command 2> error.txt - Save errors to file command > out.txt 2>&1 - Save both to same file# Standard output to file (overwrite)command > output.txt
# Standard output to file (append)command >> output.txt
# Standard error to filecommand 2> error.txt
# Redirect both stdout and stderrcommand > output.txt 2>&1command &> output.txt
# Redirect stdin from filecommand < input.txt
# Here documentcat << EOFMulti-linetext hereEOF
# Here stringcommand <<< "input string"+------------------------------------------------------------------+| Pipeline |+------------------------------------------------------------------+
+--------+ +--------+ +--------+ +--------+ | Input |---->| cmd1 |---->| cmd2 |---->| Output | +--------+ +--------+ +--------+ +--------+ | | v v +--------+ +--------+ | stdout | | stdin | +--------+ +--------+# Pipe output to another commandcommand1 | command2
# Pipeline examplesls -l | grep "pattern"cat file | sort | uniqhead -n 10 file | tail -n 54.7 Process Management
Section titled “4.7 Process Management”Viewing Processes
Section titled “Viewing Processes”+------------------------------------------------------------------+| Process Hierarchy |+------------------------------------------------------------------+
systemd (PID 1) | +--------+-----------+--------+--------+ | | | | | v v v v v sshd httpd mysqld docker nginx | | v v ssh php-fpm | v (children)# Process statuspsps auxps -ef
# Top processestophtopatop
# Specific processpgrep process_namepkill process_nameJob Control
Section titled “Job Control”+------------------------------------------------------------------+| Job Control |+------------------------------------------------------------------+
Foreground Background Jobs List +--------+ +--------+ +--------+ | Ctrl+Z | | & | | jobs | +--------+ +--------+ +--------+ | | | v v v +--------+ +--------+ +--------+ | Stop | | Run | | fg %1 | | process| | in bg | | bg %2 | +--------+ +--------+ +--------+# Run in backgroundcommand &
# View jobsjobs
# Bring to foregroundfg %job_number
# Send to background (from foreground)Ctrl+Zbg %job_number
# Kill jobkill %job_number4.8 Shell Expansion
Section titled “4.8 Shell Expansion”Types of Expansion
Section titled “Types of Expansion”+------------------------------------------------------------------+| Shell Expansion Types |+------------------------------------------------------------------+
Brace Expansion Tilde Expansion Command Substitution +----------+ +----------+ +----------+ | file{1..| | ~ | | $(date) | | 3}.txt | | ~user | | `date` | +----------+ +----------+ +----------+ | | | v v v file1.txt, /home/user Sat Mar 8... file2.txt, file3.txt
Arithmetic Expansion Parameter Expansion +----------+ +---------------+ | $((2+3)) | | ${var:-default| +----------+ | ${var#pattern}| +---------------+# Brace expansionecho {a,b,c} # a b cecho file{1..3}.txt # file1.txt file2.txt
# Tilde expansionecho ~ # /home/userecho ~user # /home/user
# Command substitutionecho $(date)echo `date`
# Arithmetic expansionecho $((2 + 3)) # 5echo $((10 / 2)) # 5Parameter Expansion
Section titled “Parameter Expansion”# Default value${var:-default} # Use default if unset${var:=default} # Set default if unset
# String operations${var#pattern} # Remove shortest match from beginning${var##pattern} # Remove longest match from beginning${var%pattern} # Remove shortest match from end${var%%pattern} # Remove longest match from end${var/old/new} # Replace first occurrence${var//old/new} # Replace all occurrences${#var} # String length4.9 Troubleshooting
Section titled “4.9 Troubleshooting”Common Shell Issues
Section titled “Common Shell Issues”+------------------------------------------------------------------+| Troubleshooting Guide |+------------------------------------------------------------------+
Problem Solution +----------------------+ +--------------------------------+ | "Command not found" | | Check PATH: echo $PATH | +----------------------+ | Add: export PATH=$PATH:/path | +--------------------------------+
+----------------------+ +--------------------------------+ | "Permission denied" | | Check: ls -l file | +----------------------+ | Fix: chmod +x script.sh | +--------------------------------+
+----------------------+ +--------------------------------+ | Variable not set | | Check: ${var:-"default"} | +----------------------+ | Test: if [ -z "$VAR" ]... | +--------------------------------+
+----------------------+ +--------------------------------+ | Quote issues | | Use " " for expansion | +----------------------+ | Use ' ' for literal | +--------------------------------+-
Command not found
Terminal window # Check PATHecho $PATH# Add to PATHexport PATH=$PATH:/new/path -
Permission denied
Terminal window # Check file permissionsls -l filename# Add execute permissionchmod +x script.sh -
Variable not set
Terminal window # Use default valueecho ${VAR:-"default"}# Check if setif [ -z "${VAR}" ]; then echo "VAR is not set"; fi -
Quotes issues
Terminal window # Double quotes allow expansionecho "Home: $HOME"# Single quotes preserve literallyecho 'Home: $HOME' # Output: Home: $HOME
4.10 Practice Exercises
Section titled “4.10 Practice Exercises”- Write a script that accepts a username and displays their information
- Create a function that calculates the factorial of a number
- Write a script that monitors a specific process and alerts if it stops
- Create a backup script that tar-gzips specified directories
- Write a script that parses a log file and extracts error messages
Quick Reference
Section titled “Quick Reference”+------------------------------------------------------------------+| Quick Reference |+------------------------------------------------------------------+
File Operations: +----------------------------------------------------------+ | ls -la | List all files with details | | cd | Change directory | | mkdir -p | Create directory tree | | rm -rf | Force remove directory | | cp -r | Copy recursively | | mv | Move/rename | +----------------------------------------------------------+
Process Management: +----------------------------------------------------------+ | ps aux | Show all processes | | top | Interactive process viewer | | kill | Send signal to process | | bg/fg | Background/foreground jobs | +----------------------------------------------------------+
Text Processing: +----------------------------------------------------------+ | grep | Search for pattern | | sed | Stream editor | | awk | Text processing | | sort/uniq | Sort and remove duplicates | +----------------------------------------------------------+