Shell Scripting and Automation
Summary
This chapter introduces shell scripting to automate repetitive tasks. You'll learn to write scripts with proper shebang lines, use variables and command-line arguments, handle exit codes, and schedule automated tasks with cron. Shell scripting is a foundational skill for system administration and DevOps.
Concepts Covered
This chapter covers the following 15 concepts from the learning graph:
- Shell Scripts
- Script Shebang
- Script Permissions
- Script Variables
- Script Arguments
- Script Exit Codes
- Cron Daemon
- Crontab Command
- Cron Syntax
- Cron Schedule Fields
- Cron Examples
- At Command
- Batch Command
- Systemd Timers
- Anacron
Prerequisites
This chapter builds on concepts from:
- Chapter 7: File Permissions and Ownership
- Chapter 11: Shell Configuration and Environment
- Chapter 12: Process Management and Job Control
Why Learn Shell Scripting?
Here's a scenario: You need to resize 500 images, rename them with a date prefix, and upload them to a server. You could do this manually (goodbye, weekend!) or you could write a script that does it in 30 seconds.
Shell scripts are the duct tape of computing—they hold everything together. They're how sysadmins automate server maintenance, how developers build deployment pipelines, and how power users save hours of repetitive work.
And here's the thing: AI tools like Claude Code are VERY good at generating shell scripts. But you still need to know what these scripts can and can't do! You need to understand:
- What the script is actually doing
- Whether it's safe to run
- How to modify it for your needs
- What could go wrong
This chapter gives you that foundation. Let's turn you into a scripting ninja!
Shell Scripts: Your First Automation
A shell script is simply a text file containing a series of commands. Instead of typing commands one by one, you put them in a file and run them all at once.
1 2 | |
1 2 3 4 5 6 | |
Script Shebang: The Magic First Line
The script shebang (or hashbang) is that weird first line: #!/bin/bash. It tells the system which interpreter to use.
1 2 3 4 5 | |
Why "shebang"? It's a combination of "hash" (#) and "bang" (!). Some old-timers call it "sha-bang" or "pound-bang." Computing history is weird.
Always Use a Shebang
Without a shebang, the script runs with whatever shell invokes it. This can cause unexpected behavior. Always be explicit!
Script Permissions: Making It Executable
Before you can run a script, you need to set script permissions to make it executable:
1 2 3 4 5 6 7 8 9 10 | |
Now you can run it:
1 2 3 4 5 6 7 8 | |
The ./ is important! It tells the shell to look in the current directory. Without it, the shell searches your PATH and probably won't find your script.
Script Variables: Storing Data
Script variables let you store and reuse values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Important variable rules:
- No spaces around the
=sign - Use
$variableor${variable}to read the value - Use quotes for strings with spaces:
message="Hello World" - Use
$(command)to capture command output
Special Variables
| Variable | Meaning |
|---|---|
$0 |
Script name |
$1, $2, ... |
Positional arguments |
$# |
Number of arguments |
$@ |
All arguments as separate words |
$* |
All arguments as one word |
$$ |
Script's process ID |
$? |
Exit code of last command |
Script Arguments: Input from Users
Script arguments let users pass data to your script:
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 | |
Processing Multiple Arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
Script Exit Codes: Success or Failure
Script exit codes tell the caller whether your script succeeded or failed. This is CRUCIAL for automation!
| Exit Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of command |
| 126 | Permission denied |
| 127 | Command not found |
| 128+N | Killed by signal N |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 | |
Exit Codes in Pipelines
In a pipeline like cmd1 | cmd2 | cmd3, the exit code is from the LAST command. Use set -o pipefail to get the first failure's exit code instead.
Real-World Scripting: Python Wrapper Scripts
One of the most common uses of shell scripts is as wrappers for complex Python programs. The shell script handles:
- Environment validation
- Path setup
- Argument preprocessing
- Error handling with user-friendly messages
While the Python code handles the actual logic.
Why Use Shell Wrappers?
- Simpler invocation:
bk-statusinstead ofpython3 /path/to/book-status.py - Environment validation: Check that required variables are set
- Dependency checking: Ensure Python, required tools are available
- Consistent error messages: Color-coded, user-friendly output
- Portable: Works the same on any system
Anatomy of a Python Wrapper Script
Here's a pattern used in real production systems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
Case Study: The Book Building Scripts
Let's look at a real-world example: the claude-skills book building scripts. This is a family of 19+ shell scripts that all use a common pattern.
The BK_HOME Environment Variable
All scripts in this family rely on a single environment variable: $BK_HOME. This points to the root of the project:
1 2 | |
Why is this brilliant?
- One variable to rule them all: Change BK_HOME, and all scripts work in a new location
- No hardcoded paths: Scripts are portable across different machines
- Easy to switch projects: Just change BK_HOME to work on a different book
The Script Family
| Script | Purpose |
|---|---|
bk |
Main menu - lists all utilities |
bk-status |
Check book project status |
bk-list-skills |
List available Claude skills |
bk-install-skills |
Install skills to ~/.claude/skills/ |
bk-resize-images |
Compress large images to ~300KB |
bk-generate-book-metrics |
Generate statistics about the book |
bk-capture-screenshot |
Capture MicroSim screenshots |
The Main Menu Script
The bk script acts as a launcher that automatically discovers other scripts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
Design Principles
This script family demonstrates several best practices:
- Consistent naming: All scripts start with
bk- - Self-documenting: Each script has a description comment
- Validation first: Check environment before doing anything
- Colored output: Easy to scan for errors vs success
- Exit codes: Proper codes for scripting and automation
- Modular: Each script does one thing well
- Discoverable: The main menu finds scripts automatically
AI-Generated Scripts: A Word of Caution
Tools like Claude Code are incredibly good at generating shell scripts. You can say "write me a script to backup my documents and compress them" and get working code in seconds.
But here's what you MUST understand:
What AI Gets Right
- Basic syntax and structure
- Common patterns and idioms
- Error handling boilerplate
- Documentation and comments
What You Need to Verify
- Does it do what you asked? Read through the logic
- Is it safe? Check for dangerous commands (rm -rf, etc.)
- Does it handle edge cases? Empty files, spaces in names, etc.
- Are the paths correct? Don't blindly trust paths
- What permissions does it need? Does it require sudo?
The Trust Hierarchy
1 2 3 | |
Never Run Scripts Blindly
Whether from AI or the internet, ALWAYS read a script before running it. A malicious script could:
- Delete your files
- Install malware
- Steal credentials
- Mine cryptocurrency
- Brick your system
When in doubt, ask Claude Code to explain what each line does!
Scheduling Tasks: Cron and Friends
Now let's automate WHEN scripts run!
The Cron Daemon
The cron daemon is a background service that runs scheduled tasks. It's been around since the 1970s and is still the go-to for automation.
1 2 3 | |
The Crontab Command
The crontab command manages your personal cron jobs:
1 2 3 4 5 6 7 8 9 10 11 | |
Cron Syntax and Schedule Fields
Cron syntax uses five cron schedule fields:
1 2 3 4 5 6 7 | |
Special characters:
| Character | Meaning | Example |
|---|---|---|
* |
Any value | * * * * * = every minute |
, |
List | 1,15,30 = at 1, 15, and 30 |
- |
Range | 1-5 = 1 through 5 |
/ |
Step | */15 = every 15 units |
Cron Examples
Here are common cron examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
Diagram: Cron Schedule Fields
Understanding the Five Cron Fields
Type: diagram
Bloom Taxonomy: Remember, Understand Learning Objective: Visualize the five cron schedule fields and their valid ranges.
Layout: Horizontal display of five boxes with field names
Visual elements: - Five connected boxes representing each field - Field names: minute, hour, day, month, weekday - Valid ranges shown below each - Example cron expression above with arrows pointing to each field
Example expressions to visualize:
- 30 2 * * * - 2:30 AM daily
- 0 */6 * * * - Every 6 hours
- 0 9 * * 1-5 - 9 AM weekdays
Interactive features: - Click each field to see valid values - Hover for explanation - Practice mode: build a cron expression
Color scheme: - Fields: Different colors (blue, green, yellow, orange, purple) - Active field: Highlighted
Implementation: p5.js
Common Crontab Tips
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Cron Environment
Cron runs with a minimal environment. Always:
- Use full paths to commands and scripts
- Set PATH at the top of your crontab
- Log output to debug problems
The At Command: One-Time Scheduling
The at command schedules a command to run once at a specific time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 | |
The Batch Command
The batch command is like at but waits until the system load is low:
1 2 3 4 5 6 7 | |
Batch is perfect for CPU-intensive tasks that shouldn't slow down your work.
Systemd Timers: Modern Scheduling
Systemd timers are the modern alternative to cron on systems using systemd. They offer:
- More precise timing
- Better logging (journalctl)
- Dependency management
- Per-service resource limits
A timer consists of two files:
The timer unit (/etc/systemd/system/backup.timer):
1 2 3 4 5 6 7 8 9 | |
The service unit (/etc/systemd/system/backup.service):
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 | |
OnCalendar Syntax
1 2 3 4 5 6 | |
Anacron: For Laptops and Desktops
Anacron is designed for machines that aren't running 24/7 (like your laptop). If a scheduled job was missed while the computer was off, anacron runs it when the machine starts up.
Configuration is in /etc/anacrontab:
1 2 3 4 | |
- period: Days between runs
- delay: Minutes to wait after boot before running
- job-identifier: Unique name (used for tracking)
- command: What to run
Anacron tracks when jobs last ran in /var/spool/anacron/.
Putting It All Together: A Complete Project
Let's create a complete backup system using everything we've learned:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
Schedule it with cron:
1 2 3 4 5 | |
Key Takeaways
You're now a scripting wizard!
- Shell scripts: Automate repetitive tasks with text files
- Shebang:
#!/bin/bashtells the system which interpreter to use - Permissions:
chmod +xmakes scripts executable - Variables: Store data with
name=value, access with$name - Arguments:
$1,$2,$@for user input - Exit codes: 0 = success, non-zero = failure
- Cron: Schedule recurring tasks with five time fields
- At: Schedule one-time tasks
- Systemd timers: Modern scheduling with better logging
- Anacron: For machines that aren't always on
- AI and scripts: Let AI generate, but always verify!
You're an Automation Master!
You can now write scripts that do the boring work for you, wrap complex programs in user-friendly interfaces, and schedule tasks to run automatically. Your future self will thank you for every script you write today!
What's Next?
Now that you can automate tasks, it's time to learn about networking—how computers talk to each other. The next chapter covers networking fundamentals, from IP addresses to SSH connections.
Quick Quiz: Shell Scripting
- What does the shebang line do?
- How do you make a script executable?
- What does
$1represent in a script? - What exit code means success?
- What are the five fields in a cron schedule?
- How is anacron different from cron?
Quiz Answers
- Tells the system which interpreter to use (e.g.,
#!/bin/bash) chmod +x script.sh- The first command-line argument passed to the script
- 0
- minute, hour, day of month, month, day of week
- Anacron runs missed jobs when the system starts; cron only runs at scheduled times
References
- Advanced Bash-Scripting Guide - Comprehensive free book covering all aspects of Bash scripting from basics to advanced.
- Bash Scripting Tutorial for Beginners - LinuxConfig step-by-step introduction to writing shell scripts.
- Shell Script Best Practices - Blog post on writing robust, maintainable shell scripts.
- Cron and Crontab Tutorial - DigitalOcean complete guide to scheduling tasks with cron.
- Understanding the Shebang - Cyberciti guide explaining shebang lines and interpreter selection.
- Bash Variables Explained - TutorialsPoint tutorial on variable types, assignment, and usage.
- Exit Codes and Error Handling - Red Hat guide to proper error handling in Bash scripts.
- Crontab Generator Tool - Interactive web tool for building and understanding cron schedules.
- Systemd Timers Tutorial - Official systemd documentation on creating timer units.
- Shell Script Security - Cyberciti article on common security pitfalls in shell scripts.
- At Command Tutorial - GeeksforGeeks guide to scheduling one-time tasks.
- Bash Functions Deep Dive - Ryan's Tutorials comprehensive guide to shell functions.
- Anacron for Desktop Linux - HowToGeek explanation of anacron for machines that aren't always on.
- Shell Script Debugging - ShellCheck online tool for finding bugs and improvements in shell scripts.
- Command-Line Arguments Processing - Baeldung tutorial on handling script arguments and options.
- Cron Log Monitoring - Guide to finding and monitoring cron job logs.
- Writing Portable Shell Scripts - GNU guide to writing scripts that work across different shells.
- Bash Arithmetic Operations - Shell Tips tutorial on performing calculations in Bash.
- Scheduling Scripts with Systemd - Opensource.com guide to replacing cron with systemd timers.
- Google Shell Style Guide - Google's official style guide for writing clean, consistent shell scripts.