Linux Shell Scripting
Linux Shell Scripting
• GNU/Linux vs Unix
• Foreground/Background Jobs
• Signals, kill, nice, renice
• SELinux/AppArmor Basics
Linux is a powerful, open-source Unix-like operating system kernel first developed by Linus
Torvalds in 1991. Unlike Windows or macOS, which are proprietary OSes, Linux is part of a
broader ecosystem where freedom, modularity, and transparency are core principles.
Technical Definition:
Characteristics:
• Multitasking
• Multi-user support
Year Milestone
• GNU (GNU’s Not Unix): Open-source tools intended to replace UNIX tools.
• Linux: Just the kernel originally. GNU + Linux = GNU/Linux (complete OS).
Think of Linux as a LEGO set — you can assemble your own operating system the way
you want.
Servers 95% of public cloud workloads (e.g., Ubuntu, RHEL, Amazon Linux)
Feature Explanation
• Text is the Universal Interface: Use plain-text config files, scripts, and logs
Popular Distros:
Category Examples
• Thousands of contributors from companies like Google, Red Hat, Intel, Meta,
Microsoft
Interesting fact: Microsoft is now one of the top 10 contributors to the Linux kernel.
• Web Servers: Apache, NGINX, HAProxy, Node.js — all commonly run on Linux
• DevOps Tools: Docker, Kubernetes, Jenkins, GitLab — all built for Linux first
• Gaming: Steam Deck uses Arch Linux; Proton enables Windows game compatibility
Metric Value
Linux is not just an OS; it’s an ecosystem, a philosophy, and the foundation of modern
computing — from smartphones and supercomputers to containers and clouds.
+----------------------------+
| User Space |
| (Applications & Shells) |
+----------------------------+
| Kernel Space |
| (Core OS: Drivers, Memory |
| Mgmt, File Systems, etc) |
+----------------------------+
• User Space: Programs, GUIs, CLI tools, shells, services
The kernel is the heart — managing CPU, memory, I/O, filesystems, and inter-process
communication (IPC).
File System Interface Mounts and manages filesystems (ext4, xfs, btrfs)
System Call Interface Provides APIs for user applications to interact with kernel
System calls like open(), read(), fork() are how userspace apps request services from the
kernel.
System calls are how user apps interact with the kernel:
Category Examples
Example in C:
if (pid == 0) {
} else {
wait(NULL); // parent
• Context Switch: CPU saves state of current process and switches to another
• Schedulers:
Tools:
Command Purpose
• VFS (Virtual File System) provides abstraction over various file systems.
Mount Example:
2.15 Summary
Linux’s architecture is highly modular, efficient, and open. Whether it’s process
management, memory allocation, or filesystem abstraction, the Linux kernel orchestrates
everything through cleanly defined interfaces and syscalls — giving you unmatched power
and flexibility.
Module 3: Filesystem Hierarchy & Linux Directories
The FHS defines the directory structure of Linux. It ensures consistent placement of files and
directories across distributions.
Top-level layout:
/
├── bin/
├── boot/
├── dev/
├── etc/
├── home/
├── lib/
├── media/
├── mnt/
├── opt/
├── proc/
├── root/
├── run/
├── sbin/
├── srv/
├── sys/
├── tmp/
├── usr/
└── var/
Each of these directories has a specific purpose, which we’ll now explore in extreme detail.
Analogy: Like C:\ in Windows — but in Linux, all disks mount under this tree.
Try:
ls /bin
• Examples:
Explore:
• Managed by udev
• Examples:
• Examples:
o /proc/cpuinfo
o /proc/meminfo
o /proc/<PID>/status
Try:
cat /proc/meminfo
Try:
cat /sys/class/net/eth0/address
Try:
ls -la /home
• Key files:
Try:
ls /boot
• Auto-cleared on reboot
• World-writable
Try:
touch /tmp/testfile
• Key subdirs:
o /var/log – Logs
Try:
tail -f /var/log/syslog
• Key subdirs:
• Example: /opt/google/chrome/
3.18 /media and /mnt – Mount Points
Directory Purpose
Command Usage
df -h Disk usage
Try:
tree -L 2 /
The Linux filesystem hierarchy is not random. Every directory has a well-defined purpose.
Knowing where logs, binaries, configs, and runtime files live is crucial for troubleshooting,
automation, and system hardening.
Module 4: Essential Linux Commands
ls -lah /etc
cd – Change Directory
cd /var/log
cd ~ # Go to home
cd - # Go to previous directory
pwd
mkdir -p /tmp/project/{logs,src,bin}
Creates nested dirs using brace expansion.
rm – Remove Files/Directories
rm -rf /tmp/project/
• -r: Recursive
cp – Copy Files
cp file.txt /tmp/
cp -r /etc /tmp/backup/
mv – Move/Rename Files
mv old.txt new.txt
mv /tmp/file.txt ~/Downloads/
cat file.txt
head -n 20 /etc/passwd
tail -f /var/log/syslog
nano file.txt
vim file.txt
• -r: Recursive
locate nginx.conf
top
kill -9 <pid>
pkill nginx
free -h
vmstat 1 5
iostat -xz 1 5
df -hT
du – Directory Size
du -sh /var/*
lsblk
Debian/Ubuntu:
RHEL/CentOS:
tar, gzip, xz
tar -czvf archive.tar.gz /home/user/
unzip project.zip
User Management
useradd devops
passwd devops
Group Management
groupadd admins
ip and ifconfig
ip a
ip r
ss -tulnp
date
uptime
hostname -I
whoami
watch -n 1 df -h
df -h | tee disk_report.txt
Linux uses:
ls -l myfile.txt
Output:
Explanation:
Examples:
Symbolic Method:
Examples:
Umask
umask 0077
5.7 Special Permissions: SUID, SGID, Sticky Bit
ls -l /usr/bin/passwd
# -rwsr-xr-x
ls -ld /shared
# drwxr-sr-x
Sticky Bit
• Common in /tmp
chmod +t /shared/tmp
ls -ld /shared/tmp
# drwxrwxrwt
Scenario Solution
Run scripts as root without sudo Use SUID carefully (only on safe binaries)
mount -o remount,acl /
Set ACLs:
getfacl file.txt
Permission Effect
r List contents
A user can access a file only if they have execute permission on all parent directories.
namei -l /var/www/html/index.html
Problem Cause
5.13 Summary
Linux permissions are the foundation of a secure system. Mastering chmod, chown, umask,
ACLs, and special bits like SUID/SGID/sticky gives you surgical control over who can do what
and protects systems from misconfiguration or intrusion.
Module 5: File/Folder Permissions in Linux – Ultra Deep Dive
Linux uses:
ls -l myfile.txt
Output:
Explanation:
Examples:
Symbolic Method:
Examples:
umask
umask 0077
5.7 Special Permissions: SUID, SGID, Sticky Bit
ls -l /usr/bin/passwd
# -rwsr-xr-x
ls -ld /shared
# drwxr-sr-x
Sticky Bit
• Common in /tmp
chmod +t /shared/tmp
ls -ld /shared/tmp
# drwxrwxrwt
Scenario Solution
Run scripts as root without sudo Use SUID carefully (only on safe binaries)
mount -o remount,acl /
Set ACLs:
getfacl file.txt
Permission Effect
r List contents
A user can access a file only if they have execute permission on all parent directories.
namei -l /var/www/html/index.html
Problem Cause
5.13 Summary
Linux permissions are the foundation of a secure system. Mastering chmod, chown, umask,
ACLs, and special bits like SUID/SGID/sticky gives you surgical control over who can do what
and protects systems from misconfiguration or intrusion.
Module 6: User and Group Management in Linux
In multi-user systems like servers, CI/CD machines, and production boxes, managing access
based on roles, privileges, and group policies ensures:
• Accountability
• Security hardening
• Separation of duties
Types of Users
Regular Users Interactive human users (UID >= 1000 on most distros)
System users can be seen using awk -F: '$3 < 1000' /etc/passwd
Each line:
username:x:UID:GID:comment:home:shell
Example:
aditya:x:1001:1001:Aditya Jaiswal:/home/aditya:/bin/bash
• UID = User ID
Create a User
Add password:
Delete a User
groupadd devops
Delete Group
groupdel devops
groups aditya
id aditya
chage -M 90 -m 7 -W 14 devopsuser
View with:
chage -l devopsuser
When you create a user with -m, contents from /etc/skel are copied into their home
directory:
/etc/skel/.bashrc
/etc/skel/.profile
You can customize these to set default env, aliases, PS1 prompt, etc.
last
Failed Logins
lastb
who
visudo
Example entry:
Summary
User and group management in Linux is more than adding users — it’s about defining access
boundaries, group roles, login security, and responsible privilege use. Mastering this helps
you enforce least privilege, secure environments, and automate account lifecycles in
corporate environments.
Module 7: Package Management in Linux
• Dependency resolution
Update repositories
Install a package
dpkg -l
dpkg -S /usr/bin/wget
Install a package
yum check-update
Update packages
Clean up cache
Install
Upgrade
Erase
List installed
rpm -qa
Repositories are remote locations that store packages and metadata. They are defined in:
sudo vi /etc/yum.repos.d/custom.repo
7.6 Third-party Tools
chmod +x myapp.AppImage
./myapp.AppImage
Broken dependencies
Corrupted cache
Conflicting versions
Linux package management is a powerful and flexible system for software delivery and
updates. Whether you're using apt, yum, dnf, rpm, snap, or flatpak, mastering the ecosystem
ensures you can manage software at scale, automate provisioning, and control
environments precisely.
Module 8: Linux Networking Commands and Tools
ip a
ip addr show
Assign IP manually
Remove IP
ifconfig
ifconfig eth0 up
route -n
8.4 Modern Replacement – ip command suite
ip route show
nslookup google.com
dig google.com
host google.com
cat /etc/resolv.conf
ping 8.8.8.8
ping google.com
traceroute google.com
curl -I https://www.example.com
wget https://www.kernel.org/pub/linux/kernel/v6.x/linux-6.0.tar.xz
8.7 Port & Socket Analysis
ss -tuln
ss -ap
netstat (legacy)
netstat -tulnp
ss -ltnp
lsof -i :8080
iperf3 -s # Server
Block an IP
hostname
hostnamectl
Change hostname
systemctl list-sockets
Scenario Command
8.13 Summary
Networking on Linux is extremely powerful and scriptable. With tools like ip, ss, tcpdump,
iptables, dig, and curl, you can diagnose, automate, and secure any network-related
operations — from debugging latency to firewalling services.
Module 9: Shell Scripting and Automation
A shell script is a plain text file containing commands to be executed by the shell interpreter
(e.g., bash, sh, zsh). It automates repetitive tasks like system updates, backups, file parsing,
CI/CD workflows, and server health checks.
Most scripting is done in bash, which we'll use throughout this module.
hello.sh
#!/bin/bash
Make it executable:
chmod +x hello.sh
./hello.sh
name="DevOps Shack"
Environment variables:
echo $HOME
export MYVAR="value"
Read input:
9.5 Conditionals
else
fi
Numeric operators:
String comparison:
fi
if [ -f myfile.txt ]; then
fi
Test Description
-f Regular file
-d Directory
-e Exists
For loop
for i in {1..5}; do
done
While loop
counter=1
((counter++))
done
Until loop
done
case $choice in
*) echo "Invalid";;
esac
9.9 Functions in Shell
greet() {
echo "Hello, $1"
}
greet "DevOps"
Return values:
bash
CopyEdit
sum() {
return $(($1 + $2))
}
sum 3 5
echo $?
done
cp file1.txt file2.txt
if [ $? -ne 0 ]; then
exit 1
fi
Suppress output:
Edit crontab:
crontab -e
Format:
* * * * * /path/to/script.sh
Field order:
Example:
0 2 * * * /backup/backup.sh
crontab -l
#!/bin/bash
URL="https://example.com"
fi
Disk Usage Alert
#!/bin/bash
fi
S3 Backup
#!/bin/bash
9.16 Summary
Shell scripting is the foundation of DevOps and automation. It empowers you to interact
with the OS, write CI/CD logic, monitor systems, manage backups, and much more — all
using native Linux tools.
Module 10: Systemd and Service Management – Ultra Deep Dive
• Bootstrapping the user space and bringing the system to operational state
• Offering powerful tools like logging, socket activation, timers, and targets
Component Purpose
unit Basic object that systemd handles (e.g., service, mount, device)
Check status
systemd-analyze
Breakdown by service
systemd-analyze blame
Type Description
[Unit]
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/myscript.py
Restart=on-failure
User=ubuntu
[Install]
WantedBy=multi-user.target
Key Sections:
Target Purpose
journalctl -u nginx
journalctl -b
journalctl -f
backup.service
[Unit]
[Service]
Type=oneshot
ExecStart=/opt/backup.sh
backup.timer
[Unit]
Description=Daily backup
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
Enable and start:
List timers:
systemctl list-timers
Problem Check
systemd is much more than a service manager — it’s a full init and event-based framework
for Linux. Mastering systemctl, .service files, journalctl, targets, and timers will allow you to
manage, troubleshoot, and automate Linux systems reliably and professionally.
Module 11: Disk, Partitioning, LVM, and Filesystems – Ultra Deep Dive
11.1 Introduction to Linux Storage Architecture
Linux treats all storage devices as files (e.g., /dev/sda, /dev/nvme0n1) and uses layers to
abstract and manage storage:
↳ LVM/RAID
lsblk -f
sudo fdisk -l
sudo blkid
df -h – Filesystem usage
df -h
du -sh /var/log
Create partitions
Within fdisk:
• n: new partition
• p: primary
• w: write changes
• d: delete
• t: change type
• q: quit without saving
Manual mount
Unmount
Filesystem Description
Create filesystem:
mkfs.ext4 /dev/sdc1
mkfs.xfs /dev/sdd1
• Thin provisioning
LVM Architecture
Shrink (careful!)
Create snapshot
Delete snapshot
mkfs.ext4 /dev/datavg/thinvol
Command Purpose
• RAID 1: Mirroring
Tool: mdadm
Create RAID 1:
[Unit]
[Mount]
What=/dev/datavg/datalv
Where=/data
Type=ext4
[Install]
WantedBy=multi-user.target
Enable it:
systemctl daemon-reload
Linux disk and volume management is highly flexible through fdisk, mkfs, mount options,
and the Logical Volume Manager (LVM). By understanding how to partition disks, create
filesystems, manage LVM snapshots, and automate mounts, you're equipped to handle real-
world infrastructure and production storage systems.
Ownership
ls -lR /secure_dir
ACLs offer per-user or per-group file permissions beyond the traditional model.
Set ACL
View ACL
getfacl file.txt
Edit safely
visudo
Used for:
• Login policies
• Password complexity
• Account lockout
vim /etc/pam.d/common-auth
Add:
Password aging
chage -M 90 -W 10 john
last
lastb
journalctl -u ssh
ausearch -k passwd_watch
Status
getenforce
sestatus
Modes:
setenforce 0
aa-status
Manage profiles
aa-complain /etc/apparmor.d/usr.sbin.mysqld
aa-enforce /etc/apparmor.d/usr.sbin.mysqld
Allow SSH
List rules
iptables -L -v -n
Persist rules
firewall-cmd --get-zones
firewall-cmd --reload
ss -tuln
Install fail2ban
View settings
sysctl -a
Block IP spoofing
sysctl -p
[Service]
ProtectSystem=full
ProtectHome=yes
PrivateTmp=yes
NoNewPrivileges=yes
These restrict filesystem access, prevent privilege escalation, and isolate services.
12.15 Summary
Mastering these tools will enable you to deploy hardened Linux environments that can
withstand internal mistakes and external threats.
Linux logs every event: service starts, kernel warnings, user logins, SSH access, disk errors,
and more. Effective troubleshooting starts with knowing:
/var/log/
File Purpose
journalctl
journalctl -u nginx
journalctl -b
journalctl -f
Used to view hardware-related messages, especially useful after boot or device failures.
dmesg | less
Check logs
journalctl -xe
df -h
df -i
Connectivity
ping google.com
traceroute google.com
DNS resolution
dig google.com
Port availability
ss -tuln
Interface config
ip a
List processes
top
htop
Memory usage
free -m
vmstat 1
iostat -xz 1
13.9 User Login Troubleshooting
last
lastb
Current sessions
who
Configuration files
/etc/logrotate.conf
/etc/logrotate.d/*
Example config
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
}
Force rotation
logrotate -f /etc/logrotate.conf
#!/bin/bash
LOGFILE="/var/log/myapp.log"
Issue Logs/Commands
Logs are your first and most valuable resource when diagnosing system behavior. Mastery of
tools like journalctl, logrotate, dmesg, and reading system logs ensures you're able to
troubleshoot complex issues in real-time and in postmortem analysis.
Module 14: Linux Performance Tuning and Resource Monitoring – Ultra Deep Dive
14.1 Why Performance Tuning Matters
• Process-level behavior
uptime
Example:
• Compare against core count for meaning (e.g., 4-core system: load 4 = 100%)
top
top
htop
htop
mpstat -P ALL 1
pidstat 1
14.4 Memory and Swap Usage
free
free -h
vmstat
vmstat 1 5
slabtop
slabtop
smem -r -k -t
iostat -xz 1 5
sudo iotop
dstat -cdnm 1
tune2fs -m 1 /dev/sda1
ss – socket summary
ss -s
ss -tulnp
iperf3 -s # Server
nice -n 10 command
renice -n -5 -p <PID>
cpulimit -l 50 -p <PID>
sysctl -a
Example tunings
sysctl -w vm.swappiness=10
sysctl -w fs.file-max=1000000
Persist in /etc/sysctl.conf
vm.swappiness=10
fs.file-max=1000000
Apply changes:
sysctl -p
ulimit -a
Permanent: /etc/security/limits.conf
perf top
strace -p <PID>
lsof -p <PID>
14.14 Summary
Performance tuning is a proactive skill that combines system knowledge with tool
proficiency. By mastering tools like top, iostat, vmstat, sysctl, pidstat, and iotop, you’ll be
able to detect, isolate, and resolve real-world bottlenecks across compute, memory, disk,
and network.
Module 15: Linux in the Cloud, Containers, and Kubernetes
• All major cloud providers (AWS, GCP, Azure) offer Linux-based VMs by default
• Tools like Docker, Kubernetes, Terraform, Jenkins are built for Linux
AWS Linux
Cloud VM lifecycle:
Cloud-init Scripts
#cloud-config
packages:
- nginx
runcmd:
• GitHub Actions, GitLab runners, CircleCI, and others default to Linux environments
• Shell scripts, deployment hooks, and pipelines are written in Bash
Linux provides native support for namespaces, cgroups, and union filesystems, making it
the backbone of container engines like Docker and Podman.
Create a container
ps aux
cat /etc/os-release
docker stats
Dockerfile example
FROM ubuntu:20.04
Node OS requirements:
Once inside:
cat /proc/cpuinfo
ps aux
df -h
15.9 Using Linux Tools for Kubernetes Debugging
Tool Usage
volumeMounts:
- mountPath: /data
name: datavol
volumes:
- name: datavol
hostPath:
path: /mnt/data
Backed by real Linux directories on the node.
securityContext:
capabilities:
drop:
- ALL
15.14 Summary
Linux is the underlying platform that powers the modern cloud and containerized world.
Whether you're managing cloud VMs, writing CI/CD pipelines, building Docker images, or
running Kubernetes nodes — Linux skills remain indispensable.