OS Notes
Shell scripting fundamentals — Bash syntax, variables, control structures, functions, command substitution, text processing, and practical automation scripts for Linux administration.
Introduction
Shell scripting is the art of writing programs for the command-line interpreter. A shell script is simply a text file containing a sequence of commands that the shell executes in order. What makes shell scripting powerful is that any command you can type manually at the terminal can be automated in a script — combining hundreds of existing Unix utilities into custom workflows without writing a single line of C or Python.
Every system administrator, DevOps engineer, and backend developer writes shell scripts regularly. They automate deployments, process log files, manage backups, monitor systems, and glue together complex pipelines. If you can work efficiently in a shell, you can be productive on any Linux system in the world.
Your First Script
#!/bin/bash
# This is a comment
echo "Hello, World!"
echo "Today is $(date)"
echo "You are logged in as: $USER"
echo "Current directory: $PWD"The first line (#!/bin/bash) is the shebang — it tells the OS which interpreter to use. Make the script executable with chmod +x script.sh, then run it with ./script.sh.
Variables
# Variable assignment (NO spaces around =)
name="Alice"
age=25
directory="/home/alice/documents"
# Using variables (dollar sign)
echo "Hello, $name! You are $age years old."
echo "Files in $directory:"
ls "$directory" # Always quote variables to handle spaces
# Read-only variable
readonly PI=3.14159
# Command substitution — store command output in variable
current_date=$(date +%Y-%m-%d)
file_count=$(ls | wc -l)
echo "Found $file_count files on $current_date"Special Variables
| Variable | Meaning |
|---|---|
$0 | Script name |
$1, $2, ...$9 | Positional parameters (arguments) |
$# | Number of arguments |
$@ | All arguments (separately quoted) |
$? | Exit status of last command (0 = success) |
$$ | Current process PID |
$! | PID of last background process |
Control Structures
Conditionals (if/elif/else)
Test Operators
Loops
Functions
Text Processing
Shell scripting excels at text manipulation using Unix tools:
# grep — search for patterns
grep "ERROR" /var/log/syslog # Lines containing ERROR
grep -c "404" access.log # Count matching lines
grep -r "TODO" ./src/ # Recursive search
# awk — column extraction and processing
awk '{print $1, $9}' access.log # Print columns 1 and 9
awk -F: '{print $1}' /etc/passwd # Use colon as delimiter
awk '$3 > 1000' /etc/passwd # Filter by condition
# sed — stream editing
sed 's/old/new/g' file.txt # Replace all occurrences
sed -n '5,10p' file.txt # Print lines 5-10
sed '/^#/d' config.txt # Delete comment lines
# cut — extract fields
cut -d: -f1,3 /etc/passwd # Fields 1 and 3, colon delimiter
# sort + uniq — frequency analysis
sort file.txt | uniq -c | sort -rn # Count unique lines, most common firstPractical Patterns
Error Handling
#!/bin/bash
set -e # Exit immediately on any error
set -u # Treat unset variables as error
set -o pipefail # Pipeline fails if any command fails
# Trap errors for cleanup
cleanup() {
echo "Cleaning up temporary files..."
rm -f /tmp/myapp_*
}
trap cleanup EXIT # Run cleanup on script exit (normal or error)Input Validation
Logging
Real-World Example: Deployment Script
Key Takeaways
- Shell scripts automate any sequence of commands you would type manually
- Always quote variables (
"$var") to prevent word splitting - Use
set -euo pipefailfor robust error handling - Functions with
localvariables keep scripts organized - Combine grep, awk, sed, and sort for powerful text processing
- Scripts should validate inputs, handle errors, and provide meaningful output
- Practice by automating tasks you do repeatedly on the command line
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Shell Scripting - Bash Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Operating Systems topic.
Search Terms
operating-systems, operating systems, operating, systems, linux, and, unix, shell
Related Operating Systems Topics