TWN Bash Scripting Handout.01
TWN Bash Scripting Handout.01
Accompanying handout for our tutorial "Bash Scripting" on TWN Youtube channel
Table of Contents
1 Introduction
3 Installation Instructions
10 Best Practices
12 Next Steps
À Real-World Impact
Shell scripting can transform tasks that take 30-45 minutes of manual
work into automated processes that run in seconds.
This handout will show you exactly how to build that automation.
Happy learning!
Nana
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
3
Understanding Shell, Bash & Terminal
Before we start writing scripts, let's decode the techy words you'll hear everywhere. Don't worry -
they're simpler than they sound!
Think of your computer like a house with two ways to control everything inside:
bash
chsh -s /bin/bash
wsl --install
bash --version
5
Sample Log Files
Create a logs directory and add sample files to follow along with the tutorial.
The sample files contain detailed log entries with timestamps, severity
levels, and various system and application messages that we'll analyze in
our scripts.
Directory Setup
mkdir logs
cd logs
touch logs/[Link]
touch logs/[Link]
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
6
Basic Linux Commands
Viewing Files
cat /path/to/[Link]
less /path/to/[Link]
head /path/to/[Link]
tail /path/to/[Link]
Searching Content
Finding Files
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
7
Basic Linux Commands
Here's what you would typically do manually (this is what we'll automate):
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
8
Creating Your First Script
Let's start with the basics. A shell script is simply a text file with Linux commands.
touch analyse_logs.sh
vim analyse_logs.sh
The lines starting with # are comments - they're ignored when the script runs, but they help us
humans understand what the code does. To make script easily readable for us!
Now how to execute - make executable? - other OS programs like python, vim, mkdir - these are all
programs, also called executables, cuz like our custom script, they are list of commands that
someone wrote that can be run/executed to run commands on our OS!
chmod +x [Link]
./[Link]
The ./ tells the shell to look for the script in the current directory. You'll see our message printed to
the screen with today's date and your username.
Creating Your First Script
Why do we have sh extension at the end?
The extension helps humans quickly identify the file as a shell script
Makes it easier to recognize script files in a directory listing
Provides a visual cue about the file's purpose and execution method
Text editors and IDEs use file extensions to enable appropriate syntax highlighting
Consistent with other scripting languages (.py, .rb, .js, etc)
Extensions Are Not Required: Unix/Linux systems execute files based on permissions and
content, not extensions. A shell script will run perfectly fine with no extension if it has executable
permissions.
So a script named [Link] could actually be a Bash, Zsh, Ksh, or POSIX shell script. The
extension itself doesn't dictate which shell interprets the script.
Now, in that case, how does interpreter know which shell program the script is written in. That9s
where what9s called a shebang statement comes in.
The #! (shebang) line at the beginning of the script determines which interpreter runs it:
So let9s add a line at start that tells the system to use the Bash interpreter for this script.
#!/bin/bash
So a shell script is simply a text file with commands, but with a special first line called a 'shebang'
that tells the system this is a script and which interpreter to use.
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
10
Creating Your First Script
Adding echo command
Now we made script code easy to read, but the output is not easy to read. The lines aren9t separated,
so it9s hard to see where each command execution and output starts and ends. Instead, we wanna
see the output with information about what the output means and separate each command
output from each other, so let9s print out this information with echo command.
IMPORTANT: -e flag, so that echo interprets escape sequences like \\n for newlines.
When you use the -e flag with echo, it tells the command to interpret backslash escape sequences
in the string instead of treating them as literal characters.
Without the -e flag, echo will print the exact characters you provide, including the backslash and the
letter following it
#!/bin/bash
11
Variables
Variables eliminate repetition and make scripts more maintainable.
Array Variables - Arrays can hold multiple values, each accessible by an index
12
Loops & Iteration
Why We Need Loops
Let's say we want to expand our script to analyze all log files in the directory - maybe logs from
different services are collected here. For each log file, we want to check multiple error patterns like
ERROR, CRITICAL, and FATAL.
If we have 10 different log files, we could write the same analysis logic 10 times for each file. But that
would mean manually checking the logs folder, copying all the file names, and pasting them in our
script. That's definitely not feasible!
Instead, we want dynamic logic that goes through any number of log files, one by one, and
executes the same analysis for each. That's where loops come in - we loop through (iterate
through) files and execute the same logic for each iteration.
#!/bin/bash
LOG_DIR="/Users/nana/logs"
ERROR_PATTERNS=("ERROR" "FATAL" "CRITICAL")
echo -e "\n==========================================================="
echo "==== Analysing log files in $LOG_DIR directory ===="
echo "==========================================================="
Loop Benefits
Automatically handles any number of files
Easily add new error patterns to the array
Consistent processing for each item
Much less code than manual repetition
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
14
File Operations
Writing Output to Files
File Redirection:
Conditionals
Conditionals allow your script to make decisions and respond differently based on specific
conditions. Think of them as "if this, then that" logic.
Why We Need Conditionals: In our log analysis script, we don't just want to count errors - we want
to be alerted when there are too many errors that need immediate attention. For example, if we find
more than 10 ERROR entries in a log file, that might indicate a serious problem requiring action.
Without conditionals, our script would just report numbers. With conditionals, our script becomes
intelligent - it can distinguish between normal situations and problems that need our attention.
Conditional Syntax:
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
15
Best Practices Summary
3. Security 4. Maintainability
Quote all variables: "$VARIABLE" Use descriptive variable names
Avoid hardcoded passwords Break long scripts into functions
Use absolute paths when possible Document complex operations
Validate user input Version control your scripts
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
16
Real World Use Cases for Practice
Each of these tasks saves significant time by automating repetitive processes, improving
efficiency, and reducing the likelihood of errors.
By practicing these use cases, you'll build a stronger foundation in shell scripting and
increase your ability to handle real-world automation challenges.
Write a script that checks the disk space usage of your system and alerts you if the disk usage
exceeds a specified threshold.
The script can then alert the admin if any parameter crosses a threshold.
Sample Task: Create a script that sends an alert when disk usage exceeds 90%
17
Learning Resources
# System monitoring
Useful Commands ps, top, htop, netstat, ss
to Explore
# Network operations
curl, wget, ssh, scp
# File operations
rsync, tar, zip, find
© nnSoftware GmbH - For more DevOps resources and tutorials, visit [Link] and YouTube channel
17
Good luck on your journey!
Remember:
18