Stop 03 · Linux & Windows FundamentalsTopics · 3/10

Bash Scripting Basics

Part of the Cybersecurity Roadmap

In short

If you type the same five commands every morning, a script can do it in one go. Small bash scripts save hours in security work, from checking logs to scanning your own lab.

Automating repetitive command-line tasks — variables, loops, conditionals — the entry point into building custom security tools and automating investigation tasks.

The blob conducts a row of small robots stacking tiffin boxes in the same order.

Think of it like this

Training a team of helpers

Write the tiffin-packing steps once, and a row of helpers can follow them exactly, every day, without mistakes. A bash script is that written routine. The computer follows it the same way each time, as fast as it can.

Watch it happen

What happens when you run ./check.sh

Shebang
Variables
Loop
If
Output

1/5The first line, #!/usr/bin/env bash, tells the system to run this file with bash.

The big ideas

What you need to know

Variables

Set with NAME=value (no spaces) and use with "$NAME". Always quote them to avoid surprises.

Loops and conditions

for, while and if cover most needs. [[ ]] is the safer test syntax in bash.

Pipes connect tools

Send one command's output into another with |. Scripts mostly glue grep, awk and sort together.

Fail safely

Start with set -euo pipefail so the script stops on errors instead of carrying on blindly.

See it in code

Walk through the code

bash
1#!/usr/bin/env bash2set -euo pipefail3 4LOG="/var/log/auth.log"5LIMIT=106 7grep "Failed password" "$LOG" | grep -oE 'from [0-9.]+' | awk '{print $2}' \8  | sort | uniq -c | while read -r count ip; do9    if [[ "$count" -gt "$LIMIT" ]]; then10      echo "ALERT: $ip had $count failed SSH logins"11    fi12  done

1/4Use bash, and stop immediately if any command fails or a variable is unset.

Run it on your own VM with sudo bash check.sh. Try a few wrong SSH passwords against it first so there's something to find.

Save yourself the pain

Common mistakes

Oops

Leaving variables unquoted, like rm $FILE.

Do this instead

Write rm "$FILE". Unquoted values with spaces or wildcards can delete the wrong things.

Oops

Testing new scripts on a real server first.

Do this instead

Test on a VM snapshot. If something breaks, roll back in seconds.

Your mission

Write a lab health check

~30 min

Quick check

Why add set -euo pipefail at the top of a bash script?

Go deeper

  1. 1Write a simple Bash script automating a repetitive task (e.g. scanning a log file for a pattern).
  2. 2Practice using variables, if/else conditionals, and a for loop in a script.
  3. 3Learn to make a script executable and run it directly.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge