← All lessons Stage 1 · Lesson 6
20 min

Bash scripting: make the terminal work for you

Stage 1 · Lesson 6 · 20 minutes · Requires Lessons 1–2


The one-line answer

A Bash script is a text file of the commands you already know, run in order — so a task you did by hand once becomes a task the computer does for you, the same way, every time.


Why you should care

In Lesson 1 you ran commands one at a time. That works for exploring. It does not work when the same check has to run on fifty log files, every morning, without mistakes.

Security work is full of repetition: counting failed logins, checking which files changed, collecting the same details from many machines. Analysts who can script do in one minute what others do in an hour — and their results are repeatable, which matters the moment someone asks "how did you get this number?"

You do not need to become a programmer. You need about ten building blocks, and they are all below.


How it actually works

Your first script

Create a file called hello.sh:

#!/bin/bash
# My first script
echo "Hello from $(hostname)"
echo "Today is $(date +%A)"

Make it executable, then run it:

chmod +x hello.sh
./hello.sh

Line by line:

  • #!/bin/bash — the shebang. It tells the system which program runs this file. Always the very first line.
  • # ... — a comment. Ignored when the script runs; it is there for humans.
  • $(command) — command substitution. Runs the command and drops its output into the line.

chmod +x is Lesson 2 in action: without the execute permission, the system refuses to run the file.

Variables

name="priya"
logfile="/var/log/auth.log"
echo "Checking $logfile for $name"

Two rules that catch every beginner:

  • No spaces around =. name = "priya" is an error — Bash reads name as a command.
  • Put variables in double quotes when you use them: "$logfile", not $logfile. Without quotes, a value containing a space splits into two separate words, and the command does something you did not intend. Later in this lesson you will see why that is a security problem, not just a bug.

Arguments — giving a script input

#!/bin/bash
# usage: ./count.sh <file> <word>
file="$1"
word="$2"
echo "Lines containing '$word' in $file:"
grep -c "$word" "$file"
./count.sh auth.log "Failed password"
SymbolMeans
$1, $2 …First, second … argument
$#How many arguments were given
$@All arguments
$0The script's own name

Exit codes — how commands report success

Every command finishes with a number. 0 means success; anything else means failure. The last one is stored in $?.

grep -q "root" /etc/passwd
echo $?        # 0 — found
grep -q "nobody-here" /etc/passwd
echo $?        # 1 — not found

This is how scripts make decisions.

Decisions with if

#!/bin/bash
file="$1"

if [ -z "$file" ]; then
  echo "usage: $0 <file>"
  exit 1
fi

if [ -f "$file" ]; then
  echo "$file exists"
else
  echo "$file not found"
  exit 1
fi

The tests you will use most:

TestTrue when
[ -f "$x" ]$x is a file
[ -d "$x" ]$x is a directory
[ -z "$x" ]$x is empty
[ "$a" = "$b" ]the two strings are equal
[ "$n" -gt 10 ]the number is greater than 10 (also -lt, -eq, -ge, -le)

The spaces inside [ and ] are required. [-f "$x"] fails.

Two shortcuts you will see everywhere:

mkdir -p reports && echo "ready"      # second runs only if the first succeeded
cd /missing || echo "could not cd"   # second runs only if the first failed

Loops

for repeats over a list:

for f in /var/log/*.log; do
  echo "$f: $(wc -l < "$f") lines"
done

while read processes a file one line at a time:

while read -r ip; do
  echo "Checking $ip"
done < suspicious_ips.txt

Functions

count_failed() {
  grep -c "Failed password" "$1"
}

echo "Failures: $(count_failed /var/log/auth.log)"

Putting it together — a real defender's script

This is the kind of script SOC analysts genuinely write. It summarises failed SSH logins in an auth log:

#!/bin/bash
# failed-logins.sh — top source IPs for failed SSH logins
# usage: ./failed-logins.sh <auth.log> [how-many]

set -euo pipefail

log="${1:-}"
top="${2:-10}"

if [ -z "$log" ] || [ ! -f "$log" ]; then
  echo "usage: $0 <auth.log> [how-many]" >&2
  exit 1
fi

total=$(grep -c "Failed password" "$log" || true)
echo "Failed SSH logins in $log: $total"
echo "Top $top source addresses:"

grep "Failed password" "$log" \
  | awk '{print $(NF-3)}' \
  | sort | uniq -c | sort -rn \
  | head -n "$top"

The new pieces:

  • set -euo pipefail — the safety line. Stop on any error (-e), treat unset variables as errors (-u), and fail if any command in a pipe fails (pipefail). Put it at the top of every script you write.
  • ${1:-} and ${2:-10} — use the argument if one was given, otherwise use a default.
  • >&2 — send the message to the error stream instead of normal output.
  • || true — grep -c exits with 1 when it finds nothing. This stops set -e treating "zero failures" as a crash.
  • \ at the end of a line — the command continues on the next line.

The pipeline at the bottom is the one-liner from Lesson 1 — now saved, named and reusable.


See it yourself

Use WSL on Windows (Stage 1 Lesson 1 showed how to install it), or the terminal on Mac or Linux.

1. Run your first script. Create hello.sh from above, chmod +x it, and run it.

2. Watch exit codes.

ls /etc > /dev/null; echo $?
ls /does-not-exist; echo $?

3. See why quotes matter.

touch "my report.txt"
f="my report.txt"
ls $f        # fails: looks for "my" and "report.txt"
ls "$f"      # works

4. Build the defender's script. Save failed-logins.sh from above and make it executable. Then create a small test log:

cat > sample-auth.log << 'EOF'
Feb 14 02:11:01 web-01 sshd[3001]: Failed password for root from 203.0.113.44 port 40001 ssh2
Feb 14 02:11:03 web-01 sshd[3002]: Failed password for admin from 203.0.113.44 port 40002 ssh2
Feb 14 02:11:05 web-01 sshd[3003]: Failed password for test from 198.51.100.7 port 40003 ssh2
Feb 14 02:11:09 web-01 sshd[3004]: Accepted publickey for analyst from 10.2.14.9 port 51422 ssh2
EOF
./failed-logins.sh sample-auth.log 5

You should see 3 failed logins, with 203.0.113.44 at the top with a count of 2.

5. Let a tool check your script. Install ShellCheck (sudo apt install shellcheck) and run shellcheck failed-logins.sh. It catches quoting mistakes and common bugs before they bite. Professionals run it on every script.

Boundary: write and run scripts on your own machine, your own virtual machine and our labs. A script that sends requests or login attempts to systems you do not own is automated unauthorised access — Stage 0 Lesson 9 applies, and automation makes it more serious, not less.


How attackers abuse this

Knowing these makes you better at preventing them.

Scripts that run as root but anyone can edit. A cron job runs /opt/backup.sh as root every night, and the file is 777. Anyone who can edit it gets their commands run as root. This is the Lesson 2 permissions mistake, and scripts are its most common victim.

Passwords written inside scripts. mysql -u admin -pSuperSecret123 saved in a script — or in .bash_history after testing it. Anyone who can read the file has the password. Searching for exactly this is routine after any foothold.

Unquoted variables in admin scripts. A cleanup script runs rm -rf $dir/*. If $dir is ever empty, that becomes rm -rf /*. If it ever contains a space, it deletes the wrong things. Quoting and checking values is a safety control, not a style preference.

Piping downloads straight into Bash. curl https://some-site/install.sh | bash runs whatever that server sends, with your permissions, before you have read a single line. If the site or the connection is tampered with, so is your machine. Download, read, then run.

Living off the land. Attackers like Bash and built-in tools because they are already installed and look normal. Defenders therefore watch what scripts do and who runs them, not merely whether Bash is running.


Common mistakes

Spaces around =. count = 5 is a command, not an assignment. Write count=5.

Forgetting quotes. "$var", almost always. Unquoted variables are the number one source of Bash bugs.

Missing spaces inside [ ]. [ -f "$x" ], not [-f "$x"].

No set -euo pipefail. Without it, a failed command is silently ignored and the script carries on with bad data — the worst kind of bug in a security report, because the numbers still look real.

Editing scripts in Windows Notepad. It saves Windows line endings, and Bash fails with $'\r': command not found. Edit inside WSL, or set your editor to use LF line endings.

Writing secrets into scripts. Read them from a protected file or an environment variable instead, and keep scripts at 700 or 750 — never 777.


Check yourself

  1. Your script says name = "priya" and fails with name: command not found. Why?
  2. Why does a script using set -e need grep -c "Failed" "$log" || true?
  3. A root cron job runs /opt/cleanup.sh, and ls -l shows -rwxrwxrwx. What is the risk, and what is the fix?
Answers
  1. Bash uses spaces to separate words, so it reads name as a command with the arguments = and "priya". Assignments must have no spaces: name="priya".
  2. grep -c exits with code 1 when it finds zero matches. Under set -e, any non-zero exit stops the script — so a perfectly normal "no failures today" would crash it. || true turns that one case into success.
  3. Any user can edit the script, and whatever they add runs as root the next time cron fires — a complete privilege escalation. The fix: owned by root, permissions 700 (or 750 if a group must read it), kept in a directory ordinary users cannot write to.

Your lab

There is no browser lab for scripting — it needs a real shell. Your practice is the See it yourself section above, on your own machine. When failed-logins.sh works on the sample log, you have finished this lesson properly.

Then add it to your portfolio: put the script in your security-writeups repository with a short README explaining what it does, how to run it, and why set -euo pipefail is there. A working, documented script is stronger evidence than a screenshot.

Finally, revisit Challenge 09 — Log file investigation and notice that your script answers its question in a single command.

→ Open Stage 1 labs


Summary in your language

தமிழ் சுருக்கம் (Tamil summary)

Bash scripting என்றால் என்ன?

Bash script என்பது நீங்கள் ஏற்கனவே தெரிந்த commands-ஐ ஒரு text file-ல் வரிசையாக எழுதி வைப்பது. ஒருமுறை கையால் செய்த வேலையை, கணினி ஒவ்வொரு முறையும் அதே மாதிரி தானாகச் செய்யும்.

அடிப்படை கட்டமைப்புகள்:

  • #!/bin/bash (shebang) — முதல் வரி. இந்த file-ஐ எந்த program இயக்க வேண்டும் என்று சொல்கிறது.
  • Variables — name="priya". = சுற்றி இடைவெளி கூடாது. பயன்படுத்தும்போது எப்போதும் "$name" என்று double quotes-ல் வையுங்கள்.
  • Arguments — $1, $2 — script-க்கு வெளியிலிருந்து கொடுக்கப்படும் உள்ளீடு.
  • Exit code — 0 என்றால் வெற்றி, மற்ற எண்கள் தோல்வி. இது $?-ல் சேமிக்கப்படும்.
  • if, for, while — முடிவுகள் எடுக்கவும், ஒரே வேலையை மீண்டும் மீண்டும் செய்யவும்.
  • set -euo pipefail — பாதுகாப்பு வரி. ஏதாவது தவறு நடந்தால் script உடனே நின்றுவிடும்.

பாதுகாப்பில் ஏன் முக்கியம்?

SOC analyst-கள் failed logins எண்ணுவது, எந்த files மாறின என்று பார்ப்பது போன்ற வேலைகளை scripts மூலம் நிமிடங்களில் முடிக்கிறார்கள். பாடத்தில் உள்ள failed-logins.sh அப்படிப்பட்ட ஒரு உண்மையான defender script.

கவனிக்க வேண்டிய ஆபத்துகள்:

  • root இயக்கும் script-ஐ எல்லோரும் மாற்ற முடிந்தால் (777), அது root அணுகலைக் கொடுப்பதற்குச் சமம். 700 அல்லது 750 பயன்படுத்துங்கள்.
  • Script-க்குள் password எழுதாதீர்கள்.
  • curl ... | bash — script-ஐப் படிக்காமல் இயக்காதீர்கள்.

எச்சரிக்கை: Scripts-ஐ உங்கள் சொந்த கணினியிலும் எங்கள் labs-லும் மட்டும் இயக்குங்கள். மற்றவர்களின் systems-க்கு எதிராக automation பயன்படுத்துவது சட்டவிரோதம்.

हिंदी सारांश (Hindi summary)

Bash scripting क्या है?

Bash script एक text file है जिसमें वही commands क्रम से लिखी होती हैं जो आप पहले से जानते हैं। जो काम आपने एक बार हाथ से किया, उसे कंप्यूटर हर बार उसी तरह अपने आप कर देता है।

बुनियादी हिस्से:

  • #!/bin/bash (shebang) — पहली line। बताती है कि इस file को कौन सा program चलाएगा।
  • Variables — name="priya"। = के आस-पास space नहीं होना चाहिए। इस्तेमाल करते समय हमेशा "$name" यानी double quotes में रखें।
  • Arguments — $1, $2 — script को बाहर से दिया गया input।
  • Exit code — 0 मतलब सफल, बाकी नंबर मतलब असफल। यह $? में रहता है।
  • if, for, while — फ़ैसले लेने और एक ही काम बार-बार करने के लिए।
  • set -euo pipefail — सुरक्षा वाली line। कोई ग़लती हो तो script तुरंत रुक जाती है।

सुरक्षा में क्यों ज़रूरी है?

SOC analysts failed logins गिनने, कौन सी files बदलीं यह देखने जैसे काम scripts से मिनटों में कर लेते हैं। इस lesson की failed-logins.sh ऐसी ही एक असली defender script है।

इन ख़तरों से बचें:

  • अगर root से चलने वाली script को कोई भी बदल सकता है (777), तो यह सबको root access देने के बराबर है। 700 या 750 रखें।
  • Script के अंदर password मत लिखें।
  • curl ... | bash — script पढ़े बिना मत चलाएँ।

चेतावनी: Scripts सिर्फ़ अपने कंप्यूटर और हमारे labs पर चलाएँ। किसी और के systems के ख़िलाफ़ automation चलाना ग़ैरक़ानूनी है।

Want this summary in Malayalam, Telugu, Kannada or another language? Tell us — the most requested languages get added next.


What's next

Bash glues commands together. When a task needs counting, messy data or talking to websites, security teams reach for Python — and you'll rebuild this lesson's script in it, then add two more tools.

→ Lesson 7: Python for security: your first useful tools