Chapter 7: Shell Scripting and
Containers
1
Chapter Overview
• Two Core Topics:
• Shell Scripting – Automating repetitive tasks using Bash scripts.
• Containers – Lightweight, isolated environments for running applications (LXC
& Docker).
• Why It Matters:
• Essential for system automation, DevOps workflows, and efficient Linux
administration.
2
Shell Scripting – Fundamentals
A shell script is simply a text file containing Linux commands that
run in sequence.
The shell (usually bash) reads the script and executes each line.
Why use shell scripts?
• Automate repetitive tasks
• Run commands without typing them manually
• Schedule tasks (cron)
• Perform system administration
Basic structure of a shell script
A shell script typically begins with a shebang:
#!/bin/bash
3
Shebang Line:
• #!/bin/bash # Specifies Bash as interpreter
• #!/bin/sh # POSIX-compliant shell
Making a Script Executable
• chmod +x [Link]
• ./[Link] # Run the script
4
This tells Linux to use bash to execute the script.
Creating your first script
[Link] the script:
nano [Link]
[Link] content:
#!/bin/bash
echo "Hello, Linux!"
[Link] and give permission to run:
chmod +x [Link]
[Link]:
./[Link]
5
1. Variables & User Input
Variables
In bash:
• No spaces around =
• Use $variable to access the value
Example:
#!/bin/bash
name="Jihad"
echo "Your name is $name"
Command substitution (store command output)
date_today=$(date)
echo "Today is $date_today "
Capture User Input:
echo "What's your name?"
read USER_NAME
echo "You entered: $USER_NAME“
• Best Practices:
• Use uppercase for global variables.
• Quote values containing spaces: VAR="My Value"
6
User Input – read
Use read to get input from the keyboard.
Example 1: Ask for user’s name
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"
Example 2: Input on same line
read -p "Enter your age: " age
echo "You are $age years old."
7
2. Conditionals (if / else / elif)
Conditionals allow a script to make decisions.
Basic syntax
if [ condition ]; then
commands
elif [ another condition ]; then
commands
else
commands
fi
8
Numeric comparisons
Operator Meaning
-eq Equal
-ne Not equal
-gt Greater than
-lt Less than
-ge Greater or equal
-le Lesser or equal
9
• Example: Compare numbers
read -p "Enter a number: " num
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
elif [ $num -eq 10 ]; then
echo "Number is equal to 10"
else
echo "Number is less than 10"
fi
String comparison
if [ "$name" == "admin" ]; then
echo "Welcome admin!"
fi
10
Control Structures – Conditionals
Basic if Statement:
if [[ $1 == "admin" ]]; then
echo "Access granted"
fi
Extended Logic:
if [[ $age -ge 18 ]]; then
echo "Adult"
elif [[ $age -ge 13 ]]; then
echo "Teen"
else
echo "Child"
fi
Logical Operators:
&& → AND (both conditions must be true)
|| → OR (at least one condition true)
11
File condition checks
Expression Meaning Example:
-f file File exists
-d dir Directory exists
if [ -f /etc/passwd ];
-x file Executable
then
-r file Readable echo "/etc/passwd
-w file Writable exists"
fi
12
3. Loops in Shell Scripting
for Loop Examples:
# Range-based
for i in {1..5}; do
echo "Loop $i"
done
# C-style
for ((i=1; i<=5; i++)); do
echo "Count: $i"
done
while Loop:
count=1
while [ $count -le 3 ]; do
echo "While loop: $count"
((count++))
done
13
• Loops allow repetition of commands.
FOR Loop
Syntax:
for item in list; do
commands
done
Example 1: Loop through numbers
for i in 1 2 3 4 5; do
echo "Number: $i"
done
Example 2: Loop through files
for file in *.txt; do
echo "Found file: $file"
done
Example 3: C-style loop
for ((i=1; i<=5; i++)); do
echo "Iteration $i"
done
14
WHILE Loop
Runs as long as the condition is true.
Example:
count=1
while [ $count -le 5 ]; do
echo "Count = $count"
count=$((count + 1))
done
UNTIL Loop
Runs until the condition becomes true (opposite of while).
Example:
i=0
until [ $i -gt 5 ]; do
echo "i = $i"
i=$((i + 1))
done
15
Putting It All Together – Example Script
#!/bin/bash
echo "Enter username:"
read user
if [ "$user" == "root" ]; then
echo "You are the superuser"
else
echo "Hello, $user!"
fi
echo "Looping through numbers 1–3:"
for i in 1 2 3; do
echo "Number: $i"
done
16
More Real World Examples
Example: Check if service is running Example: Process monitoring loop
#!/bin/bash #!/bin/bash
if systemctl is-active --quiet ssh; then while true; do
echo "SSH service is running" echo "Checking CPU usage..."
else top -b -n1 | head -n 5
echo "SSH service is NOT running" sleep 5
fi done
Example: Backup script with timestamp
#!/bin/bash
backup_file="backup_$(date +%F).[Link]"
tar -czf $backup_file /etc
echo "Backup saved as $backup_file"
17
Linux shell scripting 2
Linux shell scripting, including:
Script structure & execution
Advanced variables
Arrays
Arithmetic
Functions
Input validation
Error handling
More loops
More examples (basic → advanced)
Real administrator scripts
18
variables in shell scripting
• Types of variables
Scope (local vs environment)
Best practices and naming rules
Command substitution
Arithmetic variables
Special variables
Arrays
String manipulation
Parameter expansion
Passing arguments
19
Shell Scripting Variables — Detailed Explanation
Variables are at the core of shell scripting.
They allow you to store, manipulate, and pass data during script
execution.
1. What is a Variable?
A variable is simply a name that holds a value.
Examples:
name="Jihad"
count=10
path="/home/jihad"
No spaces before or after =
Use quotes for strings
Access value using $name
20
2. Types of Variables
There are two main categories:
A. Shell Variables (Local to the script)
Exist only in the current shell session or script.
Example:
greeting="Hello"
echo $greeting
If you open a new shell, that variable will not exist.
B. Environment Variables (Global)
Available to all child processes.
Examples:
PATH, HOME, UID, SHELL
To create an environment variable:
export NAME="Jihad"
Now all processes launched from this shell can use $NAME.
21
3. Variable Naming Rules
Must start with a letter or underscore
Can contain letters, numbers, underscore
NO spaces
NO special characters
Valid:
user_name
AGE
_file
Invalid:
2name
name-user
user*id
22
4. Assigning Variables
Simple assignment:
x=10
name="Linux"
Assigning command output:
today=$(date)
uptime_info=$(uptime)
files=$(ls /etc | wc -l)
$(command) is preferred over backticks `command`.
23
5. Reading Input into Variables
Use read:
read -p "Enter your name: " name
echo "Welcome, $name"
Silent input (password-like):
read -sp "Enter password: " pass
24
6. Special Variables
These variables are created automatically by the shell.
Example:
[Link]:
echo "First argument: $1"
echo "Script name: $0"
Run: Variable Meaning
$0 Script name
./[Link] linux
$1 … $9 Positional arguments
$# Number of arguments
$@ All arguments
$$ PID of current script
$? Exit status of last command
$USER Current user
$HOME User home directory 25
7. Arithmetic Variables
Use $(( )) for math:
a=3
b=5
sum=$((a + b))
echo $sum
Increment:
count=$((count + 1))
Or:
((count++))
26
8. Arrays (More Detailed)
Arrays store multiple values:
fruits=("apple" "banana" "orange")
Access single element:
echo ${fruits[1]} # banana
Length:
echo ${#fruits[@]}
Add items:
fruits+=("mango")
List all:
echo ${fruits[@]}
27
9. String Manipulation
Bash has built-in string operations.
Length of string
text="Linux"
echo ${#text}
Returns 5.
Substring
echo ${text:0:3}
Output:
Lin
Replace substring
message="I like Linux"
echo ${message/Linux/Ubuntu}
Output:
I like Ubuntu
28
10. Parameter Expansion (Advanced)
filename="[Link]"
echo ${filename%.txt} # result: report
Useful for scripting file management.
11. Exporting Variables (Important)
Make variable available to subprocesses:
export APP_VERSION="1.0"
Test:
echo $APP_VERSION
12. Unsetting Variables
Remove a variable:
unset name 29
13. Example Scripts Using Variables
Example 1: Greeting script
#!/bin/bash
user=$(whoami)
echo "Hello, $user!"
Example 2: Temperature conversion
#!/bin/bash
read -p "Temperature in Celsius: " c
f=$(( (c * 9/5) + 32 ))
echo "$c°C is $f°F"
30
Example 3: Check free disk space
#!/bin/bash
disk=$(df -h / | awk 'NR==2 {print $5}')
echo "Disk usage: $disk"
Example 4: Array + loop
#!/bin/bash
users=("alice" "bob" "carol")
for u in "${users[@]}"; do
echo "Creating user: $u"
useradd $u
done
31
Example 5: Script arguments
[Link]:
#!/bin/bash
src=$1
dest=$2
echo "Backing up $src to $dest..."
tar -czf "$dest" "$src"
Run:
./[Link] /etc config_backup.[Link]
32
Bonus — Admin-Level Examples
Example 6: Check if a service is running
Example 7: Monitor memory and log when low
#!/bin/bash
#!/bin/bash
service=$1
mem=$(free | awk '/Mem:/ {print $4}')
if systemctl is-active --quiet
if [ $mem -lt 100000 ]; then
$service; then
echo "Low memory: $mem" >>
echo "$service is running"
/var/log/mem_alert.log
else
fi
echo "$service is NOT running"
fi
33
Summary of Topics Covered
Topic Details
Variable basics Assignment, naming, access
Input read, silent input
Arrays access, append, length
Arithmetic $(( ))
Special variables $0, $1, $?, $$, $#
String manipulation substring, replace
Parameter expansion filename handling
Scope local, exported
Functions pass variables
Scripting examples automation, monitoring, backup
34
Shell Scripting – Deep Dive
1. What is a Shell Script?
A shell script is a text file containing Linux commands executed by a
shell (usually bash).
It automates tasks such as:
• User and system management
• Backups
• Monitoring
• Network tasks
• File operations
35
2. Script Structure
A script usually contains:
[Link]
[Link]
[Link]
[Link] (conditionals, loops)
[Link]
[Link] commands
Example structure:
#!/bin/bash
# This is a sample script
echo "Starting script..."
name="Jihad"
echo "Hello $name"
exit 0
36
3. Making a Script Executable
• chmod +x [Link]
• ./[Link]
• OR run via interpreter:
• bash [Link]
37
4. Variables (Advanced)
Basic variable:
x=10
String variable:
greeting="Hello World"
Command output in variable:
now=$(date)
Environment variable:
export PATH=$PATH:/opt/scripts
Constant (read-only):
readonly version="1.2.0"
38
5. Arrays
Arrays store multiple values.
Define an array:
colors=("red" "green" "blue")
Access elements:
echo ${colors[0]}
All elements:
echo ${colors[@]}
Append to array:
colors+=("yellow")
Loop through an array:
for c in "${colors[@]}"; do
echo "Color: $c"
done
39
6. Arithmetic in Bash
Bash supports basic arithmetic.
Using $(( )):
a=5
b=7
sum=$((a + b))
Increment:
count=$((count + 1))
Double parentheses also work in loops:
for ((i=1; i<=10; i++)); do
echo $i
done
40
7. User Input (Advanced)
Multiple inputs:
read -p "Enter username: " user
read -sp "Enter password: " pass
Validate input:
if [ -z "$user" ]; then
echo "Username cannot be empty!"
exit 1
fi
41
8. Conditionals (Advanced Examples)
String comparison:
if [ "$name" = "admin" ]; then
echo "Admin login"
fi
File checks:
if [ -d /etc ]; then
echo "/etc is a directory"
fi
if [ -f [Link] ]; then
echo "[Link] exists"
fi
Logical AND/OR:
if [ $age -gt 18 ] && [ $age -lt 60 ]; then
echo "Age is valid"
fi 42
9. Loops (More Details)
for loop with sequence:
for x in {1..5}; do
echo $x
done
while loop (infinite until break):
while true; do
echo "Running..."
sleep 2
done
until loop:
until ping -c1 [Link]; do
echo "Network down, retrying..."
sleep 3
done 43
10. Functions (Very Important)
Functions make scripts modular and reusable.
Basic function:
greet() {
echo "Hello, $1"
}
greet "Jihad"
Function with local variables:
sum() {
local a=$1
local b=$2
echo $((a + b))
}
sum 3 4 44
11. Exit Status and Error Handling
• Every command returns an exit code:
• 0 → success
• non-zero → error
• Check exit status:
• cp [Link] /backup/
• if [ $? -ne 0 ]; then
• echo "Copy failed!"
• fi
• Using set -e to exit on errors:
• set -e
45
12. Logging in Scripts
logfile="/var/log/[Link]"
echo "Backup completed at $(date)" >> "$logfile"
46
13. Real-World Scripting Examples
Example 1: Create Users Automatically
#!/bin/bash
for user in user1 user2 user3; do
useradd $user
echo "User $user created"
done
47
Example 2: System Performance Report
#!/bin/bash
echo "CPU Information:"
lscpu
echo "Memory:"
free -h
echo "Disk Usage:"
df -h
48
Example 3: Backup Script (Advanced)
#!/bin/bash
src="/etc"
dest="/backup/etc_$(date +%F).[Link]"
tar -czf $dest $src
if [ $? -eq 0 ]; then
echo "Backup successful: $dest"
else
echo "Backup failed."
fi
49
Example 4: Menu-Based Script
#!/bin/bash
echo "1) Show date" Case Statement
echo "2) Show uptime" case $input in
echo "3) Exit"
read -p "Choose an option: " option 1) echo "You chose 1";;
2) echo "You chose 2";;
case $option in
1) date ;; *) echo "Invalid";;
2) uptime ;; esac
3) exit 0 ;;
*) echo "Invalid option";;
esac
50
Example 5: Monitor a Service
#!/bin/bash
service="ssh"
if systemctl is-active --quiet $service; then
echo "$service is running"
else
echo "$service is NOT running"
echo "Attempting restart..."
systemctl restart $service
fi
51
Shell scripts that use functions
1. Basic Function Example
A simple function that prints a message.
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Linux User"
Explanation:
• The function greet() takes one argument ($1).
• It prints a message using that argument.
Output:
Hello, Linux User!
52
2. Function Returning a Value (Using echo)
Functions in bash do NOT return strings using return.
To return output, use echo.
#!/bin/bash
add() {
result=$(( $1 + $2 ))
echo $result
}
sum=$(add 5 7)
echo "Sum is: $sum"
Output:
Sum is: 12
53
3. A Function With Local Variables
Local variables do not affect the main script.
#!/bin/bash
demo() {
local x=10
echo "Inside function: x=$x"
}
x=2
demo
echo "Outside function: x=$x"
Output:
Inside function: x=10
Outside function: x=2
54
4. Script With Multiple Functions
#!/bin/bash
show_date() {
date
}
show_users() {
who
}
show_uptime() {
uptime -p
}
show_date
show_users
show_uptime
This demonstrates a multi-function tool.
55
5. A Menu Using Functions
#!/bin/bash
show_cpu() {
lscpu } case $choice in
show_disk() { 1) show_cpu ;;
df –h } 2) show_disk ;;
show_mem() { 3) show_mem ;;
free –h } 4) exit ;;
while true; do *) echo "Invalid option" ;;
echo "1) CPU Info" esac
echo "2) Disk Info"
echo "3) Memory Info" echo
echo "4) Exit" done
read -p "Choose: " choice
56
#!/bin/bash
show_cpu() {
lscpu
show_disk() {
df -h
show_mem() {
free -h
while true; do
echo "1) CPU Info"
echo "2) Disk Info"
echo "3) Memory Info"
echo "4) Exit"
read -p "Choose: " choice
case $choice in
1) show_cpu ;;
2) show_disk ;;
3) show_mem ;;
4) exit ;;
*) echo "Invalid option" ;;
esac
57
6. Function for File Existence Checking
#!/bin/bash
check_file() {
if [ -f "$1" ]; then
echo "File '$1' exists."
else
echo "File '$1' does NOT exist."
fi
}
check_file "/etc/passwd"
check_file "/file_does_not_exist"
58
7. A Function with Return Code (exit status)
To return numeric values (0–255), use return.
#!/bin/bash
is_even() {
if (( $1 % 2 == 0 )); then
return 0 # true
else
return 1 # false
fi }
is_even 6
if [ $? -eq 0 ]; then
echo "Even"
else
echo "Odd"
fi
Output:
Even 59
8. A Logging Function (Practical)
#!/bin/bash
log() {
echo "$(date +%F_%T) - $1" >>
/var/log/custom_script.log
}
log "System check started"
sleep 1
log "System check completed"
This is used in real sysadmin automation.
60
9. Backup Script Using Functions
#!/bin/bash
create_backup() {
tar -czf $[Link] $2
echo "Backup saved as $[Link]"
}
TARGET="/home/user"
FILE_NAME="backup_$(date +%F)"
create_backup "$FILE_NAME" "$TARGET"
61
10. Network Diagnostic Script (Advanced)
#!/bin/bash
ping_test() {
ping -c 1 $1 &> /dev/null
if [ $? -eq 0 ]; then
echo "$1 is reachable"
else
echo "$1 is NOT reachable"
fi }
dns_test() {
host [Link] &> /dev/null
[ $? -eq 0 ] && echo "DNS OK" || echo "DNS FAILED"
}
ping_test "[Link]"
dns_test 62
11. System Health Report Script
#!/bin/bash
cpu_info() { lscpu | grep "Model name"; }
mem_info() { free -h | grep Mem; }
disk_info() { df -h | grep "/$"; }
echo "CPU: $(cpu_info)"
echo "Memory: $(mem_info)"
echo "Disk: $(disk_info)"
63
12. Recursion in Bash (Advanced)
Not common, but possible:
#!/bin/bash
countdown() {
if [ $1 -le 0 ]; then
echo "Done!"
return
fi
echo $1
countdown $(( $1 - 1 ))
}
countdown 5
64