02 — Bash for Cybersecurity
Bash is one of the most important command-line and scripting environments for Linux-based cybersecurity work.
Security professionals regularly use Bash when working with:
LINUX SERVERS
CLOUD VMs
CONTAINERS
SECURITY TOOLS
LOG FILES
INCIDENT RESPONSE
DEVSECOPS
AUTOMATION
PENETRATION TESTING LABSThe goal of this module is not to memorize hundreds of Linux commands.
The goal is to understand how to combine small commands into repeatable security workflows.
The core Bash model is:
COMMAND ↓OUTPUT ↓PIPE ↓FILTER ↓PROCESS ↓RESULTFor example:
SECURITY LOG ↓grep ↓FILTER FAILED LOGINS ↓awk ↓EXTRACT USERS ↓sort ↓uniq ↓COUNT EVENTSThis is where Bash becomes extremely useful.
Why Bash Matters in Cybersecurity
Section titled “Why Bash Matters in Cybersecurity”Bash gives you direct access to:
FILES
DIRECTORIES
PROCESSES
SERVICES
PERMISSIONS
NETWORK CONNECTIONS
LOGS
SYSTEM CONFIGURATIONIt is therefore especially valuable for:
Security Engineers
SOC Analysts
Cloud Security Engineers
Penetration Testers
Incident Responders
DevSecOps Engineers
Linux Administrators
Threat HuntersBash Learning Path
Section titled “Bash Learning Path”Follow this sequence:
LINUX SHELL ↓FILES ↓DIRECTORIES ↓PERMISSIONS ↓PROCESSES ↓SERVICES ↓PIPES ↓REDIRECTION ↓grep ↓cut ↓sort ↓uniq ↓awk ↓sed ↓VARIABLES ↓CONDITIONS ↓LOOPS ↓FUNCTIONS ↓ARGUMENTS ↓NETWORK COMMANDS ↓LOG ANALYSIS ↓SECURITY AUTOMATION01 — Identify Your Shell
Section titled “01 — Identify Your Shell”Run:
echo "$SHELL"You may see:
/bin/bashCheck Bash version:
bash --version02 — Understand the Shell
Section titled “02 — Understand the Shell”The shell sits between:
YOU ↓COMMAND ↓SHELL ↓OPERATING SYSTEMExample:
whoamiThe shell interprets the command and displays the result.
03 — Basic Security Context
Section titled “03 — Basic Security Context”Start with:
whoamiThen:
idThen:
hostnameThen:
pwdThese answer:
WHO AM I?
WHAT GROUPS DO I HAVE?
WHICH HOST AM I ON?
WHERE AM I?04 — Command History
Section titled “04 — Command History”View your shell history:
historySecurity professionals should remember that shell history may contain sensitive information.
Avoid placing:
PASSWORDS
API KEYS
TOKENS
PRIVATE SECRETSdirectly into commands where possible.
05 — Working with Directories
Section titled “05 — Working with Directories”Show current directory:
pwdList contents:
lsDetailed view:
ls -laChange directory:
cd /var/logReturn home:
cd ~06 — Create a Practice Workspace
Section titled “06 — Create a Practice Workspace”Create:
mkdir -p ~/bash-cybersecurityMove into it:
cd ~/bash-cybersecurityCreate folders:
mkdir logs scripts reports evidenceYour structure becomes:
bash-cybersecurity/|+-- logs/|+-- scripts/|+-- reports/|+-- evidence/07 — Working with Files
Section titled “07 — Working with Files”Create a file:
touch notes.txtView:
cat notes.txtWrite:
echo "Security lab started" > notes.txtAppend:
echo "Log analysis completed" >> notes.txtRedirection Mental Model
Section titled “Redirection Mental Model”COMMAND OUTPUT ↓ > ↓FILE> overwrites.
>> appends.
08 — Standard Output and Error
Section titled “08 — Standard Output and Error”Linux commands typically use:
STDIN
STDOUT
STDERRConceptually:
INPUT ↓COMMAND ├── STANDARD OUTPUT └── STANDARD ERRORRedirect normal output:
command > output.txtRedirect errors:
command 2> errors.txtRedirect both:
command > output.txt 2>&109 — Copy and Move Files
Section titled “09 — Copy and Move Files”Copy:
cp notes.txt evidence/Move:
mv notes.txt reports/Rename:
mv old.txt new.txt10 — Remove Files Carefully
Section titled “10 — Remove Files Carefully”Remove:
rm file.txtDirectories:
rm -r directory/Be cautious with:
rm -rfespecially when running with elevated privilege.
Always verify:
pwdand the exact target before destructive operations.
11 — File Types
Section titled “11 — File Types”Use:
file <filename>Example:
file security.logThis can help identify whether something is:
TEXT
EXECUTABLE
ARCHIVE
IMAGE
BINARY12 — View File Metadata
Section titled “12 — View File Metadata”Use:
stat security.logThis provides:
Size
Owner
Permissions
Timestamps
Filesystem Information13 — Linux Permissions
Section titled “13 — Linux Permissions”Run:
ls -lExample:
-rw-r----- 1 analyst security 1024 Aug 29 security.logInterpret:
OWNER
GROUP
OTHERSwith:
READ
WRITE
EXECUTE14 — Permission Values
Section titled “14 — Permission Values”Common numeric values:
4 = Read
2 = Write
1 = ExecuteExample:
750means:
OWNERrwx
GROUPr-x
OTHERS---15 — Change Permissions
Section titled “15 — Change Permissions”In your own lab:
chmod 640 security.logFor a script:
chmod 750 script.sh16 — Review Ownership
Section titled “16 — Review Ownership”Use:
ls -lChange ownership only when authorized and required.
Example administrative form:
sudo chown user:group fileDo not change ownership on production systems without approval.
17 — Security Importance of Permissions
Section titled “17 — Security Importance of Permissions”A key Linux security question is:
WHO CAN READ?
WHO CAN WRITE?
WHO CAN EXECUTE?Especially for:
CONFIGURATION FILES
SCRIPTS
SERVICE FILES
LOGS
CREDENTIAL FILES
PRIVATE KEYS18 — Find Files
Section titled “18 — Find Files”Find by name:
find . -name "*.log"Find directories:
find . -type dFind files:
find . -type f19 — Find Recently Modified Files
Section titled “19 — Find Recently Modified Files”For incident response in an authorized system:
find . -type f -mtime -1This finds files modified within approximately the last day.
20 — Find Large Files
Section titled “20 — Find Large Files”Example:
find . -type f -size +10MUseful for:
LOG REVIEW
DISK INVESTIGATION
EVIDENCE COLLECTION21 — Find Files by Permission
Section titled “21 — Find Files by Permission”In your own lab:
find . -type f -perm -002This identifies world-writable files in the current tree.
Do not assume every result is automatically a vulnerability.
22 — Pipes
Section titled “22 — Pipes”The pipe operator:
|passes output from one command into another.
Example:
cat security.log | grep "FAILED"More simply:
grep "FAILED" security.logPipe Mental Model
Section titled “Pipe Mental Model”COMMAND A ↓OUTPUT ↓| ↓COMMAND B23 — grep
Section titled “23 — grep”grep is one of the most useful Linux security commands.
Example:
grep "FAILED" security.logCase-insensitive:
grep -i "failed" security.logShow line numbers:
grep -n "FAILED" security.log24 — Recursive grep
Section titled “24 — Recursive grep”Search through a directory you are authorized to inspect:
grep -R "ERROR" ./logsUseful for:
LOGS
APPLICATION CONFIGURATION
INCIDENT REVIEWAvoid broad secret-hunting across systems without a legitimate need.
25 — Invert Matching
Section titled “25 — Invert Matching”Show lines not matching:
grep -v "INFO" security.logThis can remove noise.
26 — Count Matching Lines
Section titled “26 — Count Matching Lines”grep -c "FAILED" security.log27 — cut
Section titled “27 — cut”cut extracts fields.
Example file:
admin01,10.10.10.20,FAILEDuser01,10.10.10.30,SUCCESSExtract first column:
cut -d',' -f1 events.csv28 — sort
Section titled “28 — sort”Sort lines:
sort users.txtNumeric sort:
sort -n numbers.txtReverse:
sort -r users.txt29 — uniq
Section titled “29 — uniq”Remove adjacent duplicates:
sort users.txt | uniqCount:
sort users.txt | uniq -cSecurity Example
Section titled “Security Example”cut -d',' -f1 events.csv | sort | uniq -cThis can count events by user.
30 — head and tail
Section titled “30 — head and tail”First lines:
head security.logLast lines:
tail security.logLast 20 lines:
tail -n 20 security.log31 — Follow Logs in Real Time
Section titled “31 — Follow Logs in Real Time”For your own lab:
tail -f application.logThis is useful while validating:
APPLICATION EVENTS
AUTHENTICATION EVENTS
SERVICE ACTIVITYStop with:
Ctrl+C32 — wc
Section titled “32 — wc”Count lines:
wc -l security.logCount words:
wc -w security.log33 — awk
Section titled “33 — awk”awk is powerful for structured text processing.
Suppose:
FAILED admin01 10.10.10.20SUCCESS user01 10.10.10.30Extract username:
awk '{print $2}' security.logExtract IP:
awk '{print $3}' security.log34 — Filter with awk
Section titled “34 — Filter with awk”awk '$1 == "FAILED" {print $2, $3}' security.logThis prints users and IPs for failed events.
35 — Count Failed Logins by User
Section titled “35 — Count Failed Logins by User”Example:
awk '$1 == "FAILED" {print $2}' security.log |sort |uniq -c |sort -nrWorkflow:
LOG ↓FILTER FAILED ↓EXTRACT USER ↓SORT ↓COUNT ↓RANK36 — sed
Section titled “36 — sed”sed transforms text.
Example:
sed 's/FAILED/LOGIN_FAILURE/g' security.logBy default this prints the transformed result rather than changing the original file.
37 — Safe sed Practice
Section titled “37 — Safe sed Practice”Preview first:
sed 's/old/new/g' file.txtOnly modify files in place when you understand the impact and have a backup.
38 — tr
Section titled “38 — tr”Translate characters.
Example:
echo "HIGH" | tr 'A-Z' 'a-z'Output:
highThis is useful for normalizing security data.
39 — xargs
Section titled “39 — xargs”xargs can convert input into command arguments.
Example:
printf "%s\n" file1.txt file2.txt | xargs -n1 basenameUse caution when input comes from untrusted sources or filenames containing unusual characters.
40 — Variables
Section titled “40 — Variables”Create:
username="analyst01"Print:
echo "$username"41 — Security Variables
Section titled “41 — Security Variables”Example:
log_file="./logs/auth.log"report_file="./reports/failed-logins.txt"threshold=5Use descriptive names.
42 — Quoting
Section titled “42 — Quoting”Double quotes expand variables:
echo "$username"Single quotes do not:
echo '$username'Understanding quoting is essential for writing safe shell scripts.
43 — Command Substitution
Section titled “43 — Command Substitution”Capture command output:
current_user=$(whoami)Then:
echo "Current user: $current_user"44 — Environment Variables
Section titled “44 — Environment Variables”View:
envor:
printenvCommon variables:
PATH
HOME
USER
SHELL45 — PATH
Section titled “45 — PATH”Display:
echo "$PATH"One directory per line:
echo "$PATH" | tr ':' '\n'Security scripts should avoid relying on unsafe or unexpected command-resolution paths.
46 — Script Creation
Section titled “46 — Script Creation”Create:
nano scripts/security-check.shStart with:
#!/usr/bin/env bash
echo "Security check started"Make executable:
chmod +x scripts/security-check.shRun:
./scripts/security-check.sh47 — Shebang
Section titled “47 — Shebang”The first line:
#!/usr/bin/env bashtells the operating system which interpreter should execute the script.
48 — Script Safety Options
Section titled “48 — Script Safety Options”For many automation scripts, consider:
set -euo pipefailConceptually:
-eStop on unhandled command failure
-uFail on unset variables
pipefailPropagate pipeline failuresUnderstand how these affect your script before using them.
49 — Conditions
Section titled “49 — Conditions”Example:
failed_logins=8
if [ "$failed_logins" -gt 5 ]; then echo "Suspicious login activity"fi50 — if / else
Section titled “50 — if / else”if [ "$failed_logins" -gt 10 ]; then echo "High risk"else echo "Review normally"fi51 — if / elif / else
Section titled “51 — if / elif / else”if [ "$failed_logins" -ge 10 ]; then echo "High"elif [ "$failed_logins" -ge 5 ]; then echo "Medium"else echo "Low"fi52 — Numeric Operators
Section titled “52 — Numeric Operators”Common:
-eq Equal
-ne Not equal
-gt Greater than
-lt Less than
-ge Greater or equal
-le Less or equal53 — String Comparisons
Section titled “53 — String Comparisons”Example:
severity="critical"
if [ "$severity" = "critical" ]; then echo "Escalate"fi54 — File Tests
Section titled “54 — File Tests”Check file exists:
if [ -f "$log_file" ]; then echo "Log found"fiDirectory:
if [ -d "./logs" ]; then echo "Logs directory exists"fiReadable:
if [ -r "$log_file" ]; then echo "Readable"fi55 — Loops
Section titled “55 — Loops”Example:
for host in WEB01 APP01 DB01; do echo "Reviewing $host"done56 — Loop Through Files
Section titled “56 — Loop Through Files”for file in ./logs/*.log; do echo "Processing $file"doneHandle cases where no files match carefully in production-quality scripts.
57 — while Loops
Section titled “57 — while Loops”Example:
count=1
while [ "$count" -le 3 ]; do echo "Iteration $count" count=$((count + 1))done58 — Read a File Line by Line
Section titled “58 — Read a File Line by Line”A safer pattern:
while IFS= read -r line; do echo "$line"done < security.logThis preserves most input accurately.
59 — Functions
Section titled “59 — Functions”Create reusable logic:
show_alert() { echo "ALERT: $1"}Call:
show_alert "Multiple failed logins detected"60 — Return vs Output
Section titled “60 — Return vs Output”Shell functions commonly return a numeric status and print output separately.
Example:
check_file() { if [ -f "$1" ]; then return 0 else return 1 fi}Then:
if check_file "security.log"; then echo "File exists"fi61 — Script Arguments
Section titled “61 — Script Arguments”Arguments are:
$1
$2
$3Example:
#!/usr/bin/env bash
log_file="$1"
echo "Analyzing $log_file"Run:
./analyze.sh security.log62 — Argument Validation
Section titled “62 — Argument Validation”Always validate.
if [ "$#" -ne 1 ]; then echo "Usage: $0 <logfile>" exit 1fi63 — Validate File Input
Section titled “63 — Validate File Input”log_file="$1"
if [ ! -f "$log_file" ]; then echo "File not found" exit 1fi64 — Exit Codes
Section titled “64 — Exit Codes”Convention:
0=Success
Non-zero=Error / Other StatusCheck the previous result:
echo "$?"65 — Logical Operators
Section titled “65 — Logical Operators”AND:
command1 && command2Second command runs only if the first succeeds.
OR:
command1 || command2Second command runs if the first fails.
66 — Group Commands Carefully
Section titled “66 — Group Commands Carefully”Example:
mkdir -p reports &&echo "Reports directory ready"This is useful for predictable automation.
67 — Process Review
Section titled “67 — Process Review”Use:
ps auxor:
ps -efLook for:
User
PID
Process
Arguments68 — Search Processes
Section titled “68 — Search Processes”ps aux | grep "application"A cleaner option may be:
pgrep -a applicationwhen available.
69 — Process Tree
Section titled “69 — Process Tree”Use:
ps -ef --forestor:
pstreeThis helps understand:
PARENT
CHILD
SERVICE RELATIONSHIPS70 — System Services
Section titled “70 — System Services”On systemd systems:
systemctl --type=service --state=runningInspect:
systemctl status <service>71 — Logs with journalctl
Section titled “71 — Logs with journalctl”View service logs:
journalctl -u <service>Recent entries:
journalctl -u <service> -n 50Since today:
journalctl --since today72 — Authentication Logs
Section titled “72 — Authentication Logs”Depending on distribution, logs may exist at:
/var/log/auth.log
/var/log/secureOnly inspect logs you are authorized to access.
73 — Failed Login Analysis
Section titled “73 — Failed Login Analysis”Example:
grep -i "failed" /path/to/training-auth.logCount:
grep -ic "failed" /path/to/training-auth.log74 — Build a Failed Login Pipeline
Section titled “74 — Build a Failed Login Pipeline”Example synthetic log:
FAILED admin01 10.10.10.21FAILED user01 10.10.10.22FAILED admin01 10.10.10.23FAILED admin01 10.10.10.21Run:
awk '$1 == "FAILED" {print $2}' auth.log |sort |uniq -c |sort -nrOutput might be:
3 admin011 user0175 — Count by Source IP
Section titled “75 — Count by Source IP”awk '$1 == "FAILED" {print $3}' auth.log |sort |uniq -c |sort -nr76 — Generate a Report
Section titled “76 — Generate a Report”awk '$1 == "FAILED" {print $2}' auth.log |sort |uniq -c |sort -nr > reports/failed-users.txt77 — Add a Timestamp
Section titled “77 — Add a Timestamp”dateFormatted:
date '+%Y-%m-%d %H:%M:%S'Use in reports:
echo "Generated: $(date '+%Y-%m-%d %H:%M:%S')" \> reports/report.txt78 — File Hashing
Section titled “78 — File Hashing”Use:
sha256sum sample.txtSecurity uses:
INTEGRITY
EVIDENCE
IOC COMPARISON
FILE TRACKING79 — Hash Multiple Files
Section titled “79 — Hash Multiple Files”sha256sum evidence/*Only use files you are authorized to process.
80 — Verify Hash
Section titled “80 — Verify Hash”Save:
sha256sum sample.txt > sample.sha256Verify:
sha256sum -c sample.sha25681 — Archives
Section titled “81 — Archives”Create:
tar -czf evidence.tar.gz evidence/List contents:
tar -tzf evidence.tar.gzThis can help package lab evidence.
82 — Network Configuration
Section titled “82 — Network Configuration”Use:
ip addrRoutes:
ip routeDNS configuration varies by system, but may be reviewed through appropriate resolver configuration.
83 — Listening Ports
Section titled “83 — Listening Ports”Use:
ss -lntupThis can show:
Local Address
Port
Protocol
Processdepending on permissions.
84 — Established Connections
Section titled “84 — Established Connections”Use:
ss -ntpReview:
Local Endpoint
Remote Endpoint
State85 — DNS Lookup
Section titled “85 — DNS Lookup”Use:
dig example.comor:
nslookup example.comFor security labs, use authorized internal names where appropriate.
86 — HTTP Requests
Section titled “86 — HTTP Requests”Use:
curl https://example.comHeaders:
curl -I https://example.comVerbose:
curl -v https://example.comUse only against systems you are authorized to interact with.
87 — Work with APIs Using curl
Section titled “87 — Work with APIs Using curl”Example placeholder:
curl \ -H "Accept: application/json" \ https://example.invalid/api/status88 — Protect API Credentials
Section titled “88 — Protect API Credentials”Avoid:
curl -H "Authorization: Bearer real-secret" ...in situations where the token may be exposed in history or process information.
Prefer approved secure secret handling for the environment.
89 — Download Files Safely
Section titled “89 — Download Files Safely”Example:
curl -o file.txt https://example.invalid/file.txtOnly download from trusted and authorized sources.
Verify expected hashes where available.
90 — Disk Usage
Section titled “90 — Disk Usage”Use:
df -hDirectory size:
du -sh ./logsIdentify large entries:
du -sh ./* | sort -h91 — Memory and CPU Context
Section titled “91 — Memory and CPU Context”Use:
free -hand:
uptimeThese are useful during:
INCIDENT RESPONSE
SYSTEM TROUBLESHOOTING
SERVICE INVESTIGATION92 — Environment Review
Section titled “92 — Environment Review”Run:
envBe careful when capturing evidence because environment variables may contain sensitive configuration.
Redact secrets.
93 — Shell Script Logging
Section titled “93 — Shell Script Logging”Example:
log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $1"}Then:
log "Analysis started"94 — Write Logs to a File
Section titled “94 — Write Logs to a File”log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $1" \ >> reports/script.log}Do not write secrets to logs.
95 — Error Handling
Section titled “95 — Error Handling”Example:
if ! grep "FAILED" security.log > /dev/null; then echo "No failed events detected or command failed"fiFor production scripts, distinguish:
NO MATCH
COMMAND FAILUREwhen necessary.
96 — Temporary Files
Section titled “96 — Temporary Files”Avoid predictable temporary filenames for sensitive operations.
Use:
mktempExample:
temp_file=$(mktemp)Clean up:
rm -f "$temp_file"97 — trap
Section titled “97 — trap”Use trap for cleanup:
temp_file=$(mktemp)
cleanup() { rm -f "$temp_file"}
trap cleanup EXITThis helps remove temporary resources even when the script exits unexpectedly.
98 — Avoid Unsafe eval
Section titled “98 — Avoid Unsafe eval”Avoid patterns involving:
eval "$user_input"especially with untrusted data.
It can cause input to be interpreted as shell commands.
99 — Quote Variables
Section titled “99 — Quote Variables”Prefer:
rm -- "$file"not:
rm $fileQuoting helps prevent whitespace and special-character problems.
100 — Use -- Where Appropriate
Section titled “100 — Use -- Where Appropriate”Some commands support:
--to indicate the end of options.
Example:
rm -- "$filename"This is useful when filenames could begin with -.
101 — Avoid Parsing ls
Section titled “101 — Avoid Parsing ls”Do not build scripts around patterns like:
for file in $(ls)This breaks on spaces and unusual filenames.
Prefer:
for file in ./*; do ...doneor appropriate find patterns.
102 — Security Script Structure
Section titled “102 — Security Script Structure”A reusable script can follow:
SHEBANG
SAFETY OPTIONS
CONFIGURATION
FUNCTIONS
INPUT VALIDATION
MAIN WORKFLOW
OUTPUT
CLEANUP103 — Example Structure
Section titled “103 — Example Structure”#!/usr/bin/env bash
set -u
main() { echo "Security analysis started"}
main "$@"104 — Project 01: Failed Login Analyzer
Section titled “104 — Project 01: Failed Login Analyzer”Build:
AUTH LOG ↓FILTER FAILURES ↓EXTRACT USERS ↓COUNT ↓SORT ↓REPORTExample pipeline:
awk '$1 == "FAILED" {print $2}' auth.log |sort |uniq -c |sort -nr105 — Project 02: Suspicious IP Summary
Section titled “105 — Project 02: Suspicious IP Summary”Input:
FAILED admin01 10.10.10.20FAILED admin01 10.10.10.20FAILED user01 10.10.10.30Process:
awk '$1 == "FAILED" {print $3}' auth.log |sort |uniq -c |sort -nrOutput:
Count by Source IP106 — Project 03: File Integrity Baseline
Section titled “106 — Project 03: File Integrity Baseline”Create a baseline:
find evidence -type f -exec sha256sum {} \; \> reports/baseline.sha256Later compare carefully using your training data.
This introduces the concept of:
FILE INTEGRITY MONITORING107 — Project 04: Linux Security Inventory
Section titled “107 — Project 04: Linux Security Inventory”Create a script that records:
Hostname
Current User
OS
Kernel
IP Addresses
Routes
Listening Ports
Running Services
Disk UsageDo not include secrets.
108 — Project 05: Security Log Report
Section titled “108 — Project 05: Security Log Report”Build:
INPUT LOG ↓FAILED EVENTS ↓ERROR EVENTS ↓TOP USERS ↓TOP SOURCES ↓REPORT FILE109 — Project 06: Permission Review
Section titled “109 — Project 06: Permission Review”Within your own training directory:
FILES ↓PERMISSIONS ↓WORLD-WRITABLE ↓GROUP-WRITABLE ↓REPORTFocus on explaining permissions rather than labeling every writable object a vulnerability.
110 — Project 07: Service Inventory
Section titled “110 — Project 07: Service Inventory”Collect:
RUNNING SERVICES
LISTENING PORTS
SERVICE NAMES
SYSTEM ROLEThen manually review whether each service is expected.
111 — Project 08: Evidence Collection Helper
Section titled “111 — Project 08: Evidence Collection Helper”Build a script that:
Creates Evidence Folder
Records Timestamp
Records Hostname
Records User
Calculates File Hashes
Creates Archive
Generates Evidence IndexUse only inside your authorized lab.
112 — Bash for SOC Analysts
Section titled “112 — Bash for SOC Analysts”Focus on:
grep
awk
sort
uniq
cut
Log Analysis
IOC Processing
Report Generation113 — Bash for Incident Responders
Section titled “113 — Bash for Incident Responders”Focus on:
Processes
Network Connections
Recent Files
Hashes
Logs
Services
Evidence Collection114 — Bash for Cloud Security
Section titled “114 — Bash for Cloud Security”Focus on:
Cloud CLI Output
JSON / Text Processing
Resource Inventory
Configuration Checks
Log Collection
AutomationWhen structured JSON is available, dedicated parsers such as jq are often preferable to fragile text parsing.
115 — jq for JSON
Section titled “115 — jq for JSON”If installed:
jq '.'can format JSON.
Example:
cat events.json | jq '.'More simply:
jq '.' events.json116 — Extract JSON Fields
Section titled “116 — Extract JSON Fields”Given:
{ "user": "analyst01", "severity": "high"}Use:
jq -r '.user' event.json117 — Filter JSON
Section titled “117 — Filter JSON”Example array:
jq '.[] | select(.severity == "high")' alerts.jsonThis is useful for cloud and security API data.
118 — Bash vs Python
Section titled “118 — Bash vs Python”Use Bash when:
The Task Is Shell-Oriented
You Are Combining Linux Commands
The Workflow Is Short
You Need Quick AutomationUse Python when:
Data Structures Become Complex
Logic Becomes Large
You Need Robust APIs
You Need Advanced Error Handling
The Script Must Scale119 — When Bash Becomes Too Large
Section titled “119 — When Bash Becomes Too Large”A useful rule:
IF THE SCRIPT BECOMESDIFFICULT TO READ,TEST, OR MAINTAINconsider moving the workflow to:
PYTHONor another suitable language.
120 — Bash Security Principles
Section titled “120 — Bash Security Principles”Always think about:
QUOTING
INPUT VALIDATION
FILE PERMISSIONS
SECRET HANDLING
TEMPORARY FILES
ERROR HANDLING
LEAST PRIVILEGE
CLEANUP121 — Never Hard-Code Secrets
Section titled “121 — Never Hard-Code Secrets”Avoid:
password="real-password"or:
token="real-token"in scripts committed to repositories.
Use approved secret-management mechanisms for your environment.
122 — Least Privilege
Section titled “122 — Least Privilege”Do not run:
sudo ./script.shsimply because the script fails.
Determine:
WHICH ACTIONNEEDS ADDITIONAL PRIVILEGE?and whether that privilege is actually necessary.
123 — Protect Script Files
Section titled “123 — Protect Script Files”Security automation scripts themselves may become sensitive if they:
ACCESS PRIVILEGED DATA
READ CREDENTIAL STORES
MANAGE SERVICES
ACCESS CLOUD APIsProtect them appropriately.
124 — Review Before Running Scripts
Section titled “124 — Review Before Running Scripts”Before executing an unfamiliar script:
READ IT
UNDERSTAND IT
CHECK INPUTS
CHECK FILE OPERATIONS
CHECK NETWORK OPERATIONS
CHECK PRIVILEGES
CHECK CLEANUPDo not blindly run copied scripts as root.
125 — 4-Week Bash Practice Plan
Section titled “125 — 4-Week Bash Practice Plan”| Week | Focus |
|---|---|
| 1 | Shell, Files, Permissions, Pipes |
| 2 | grep, awk, sed, sort, uniq |
| 3 | Variables, Conditions, Loops, Functions |
| 4 | Logs, Networking, Security Automation |
126 — Daily Bash Practice
Section titled “126 — Daily Bash Practice”Use:
DAY 01FILES
DAY 02PERMISSIONS
DAY 03PIPES
DAY 04grep
DAY 05awk
DAY 06LOG ANALYSIS
DAY 07MINI PROJECTThen repeat with more complex security data.
Bash Readiness Levels
Section titled “Bash Readiness Levels”Level 01 — Linux Navigation
Section titled “Level 01 — Linux Navigation”You can use:
pwd
cd
ls
cat
cp
mvLevel 02 — Security Data Processing
Section titled “Level 02 — Security Data Processing”You can combine:
grep
cut
sort
uniq
head
tail
wcLevel 03 — Advanced Text Processing
Section titled “Level 03 — Advanced Text Processing”You can use:
awk
sed
jqappropriately.
Level 04 — Bash Scripting
Section titled “Level 04 — Bash Scripting”You understand:
Variables
Conditions
Loops
Functions
ArgumentsLevel 05 — Linux Security Operations
Section titled “Level 05 — Linux Security Operations”You can review:
Processes
Services
Network Connections
Logs
PermissionsLevel 06 — Security Automation
Section titled “Level 06 — Security Automation”You can build scripts that:
Collect
Parse
Analyze
Report
Clean UpBash for Cybersecurity Checklist
Section titled “Bash for Cybersecurity Checklist”Shell Fundamentals
Section titled “Shell Fundamentals”- Shell identified
- Current user identified
- Host identified
- Working directory understood
- History understood
- Create files
- Read files
- Copy files
- Move files
- Remove files safely
- File metadata reviewed
Permissions
Section titled “Permissions”-
ls -l - Read/write/execute understood
- Numeric permissions understood
- Ownership understood
-
chmodunderstood
Text Processing
Section titled “Text Processing”- grep
- cut
- sort
- uniq
- head
- tail
- wc
- awk
- sed
- tr
Shell Programming
Section titled “Shell Programming”- Variables
- Quoting
- Command substitution
- Conditions
- Loops
- Functions
- Arguments
- Exit codes
Processes
Section titled “Processes”-
ps - Process tree
- Process filtering
- Services
- systemd
- Authentication logs
- Application logs
-
journalctl - Filtering
- Counting
- Reporting
Networking
Section titled “Networking”-
ip addr -
ip route -
ss - DNS lookup
-
curl
Security Utilities
Section titled “Security Utilities”- SHA-256
- Archive evidence
- Timestamp reports
- Temporary files
- Cleanup
- JSON concept understood
-
jqformatting - Field extraction
- Filtering
Secure Scripting
Section titled “Secure Scripting”- Variables quoted
- Inputs validated
- Secrets protected
- Least privilege used
- Errors handled
- Temporary files handled safely
- Cleanup performed
- Unfamiliar scripts reviewed before execution
Projects
Section titled “Projects”- Failed login analyzer
- Suspicious IP summary
- File integrity baseline
- Linux inventory
- Log report
- Permission review
- Service inventory
- Evidence helper
40 Bash for Cybersecurity Review Questions
Section titled “40 Bash for Cybersecurity Review Questions”- What is Bash?
- Why is Bash useful for cybersecurity?
- What does
whoamishow? - What does
idshow? - What does
pwdshow? - What does
ls -laprovide? - What do Linux read, write, and execute permissions mean?
- What does
chmoddo? - What is standard output?
- What is standard error?
- What does
>do? - What does
>>do? - What is a pipe?
- What does
grepdo? - What does
cutdo? - Why are
sortanduniqoften used together? - What is
awkuseful for? - What is
sedused for? - What does
tail -fdo? - What is command substitution?
- What is an environment variable?
- Why is PATH security-sensitive?
- What is a shebang?
- What does
set -udo? - What is an exit code?
- What does
$?represent? - What are positional arguments?
- Why should script arguments be validated?
- What does
ps auxshow? - What does
systemctlmanage? - What does
journalctlprovide? - What does
ssshow? - Why are file hashes useful?
- What does
mktemphelp with? - What does
traphelp automate? - Why should variables normally be quoted?
- Why can
evalbe dangerous? - Why should Bash scripts use least privilege?
- When should you consider replacing Bash with Python?
- What makes a Bash security workflow repeatable?
Final Bash for Cybersecurity Mental Model
Section titled “Final Bash for Cybersecurity Mental Model”Remember:
LINUX SECURITY DATA ↓COMMAND ↓PIPE ↓FILTER ↓TRANSFORM ↓COUNT / CORRELATE ↓REPORTFor scripting:
INPUT ↓VALIDATE ↓PROCESS ↓DECISION ↓OUTPUT ↓LOG ↓CLEANUPDo not think:
I NEED TO MEMORIZEEVERY LINUX COMMANDThink:
WHAT INFORMATIONDO I NEED?
WHICH COMMANDPRODUCES IT?
HOW DO I FILTERTHE OUTPUT?
HOW DO I TURN ITINTO A SECURITY RESULT?For example:
AUTHENTICATION LOG ↓grep / awk ↓FAILED EVENTS ↓sort / uniq ↓EVENT COUNTS ↓SECURITY REVIEWor:
LINUX HOST ↓PROCESSES +SERVICES +PORTS +PERMISSIONS ↓SECURITY INVENTORYThat is the real power of Bash for cybersecurity:
SMALL COMMANDS +SHELL LOGIC +SECURITY CONTEXT =POWERFUL AUTOMATIONWhat’s Next?
Section titled “What’s Next?”➡️ 03 — PowerShell for Cybersecurity
The next module moves from Linux security automation into the Windows and Microsoft ecosystem.
You will learn:
POWERSHELL SHELL ↓CMDLETS ↓OBJECTS ↓PIPELINE ↓VARIABLES ↓CONDITIONS ↓LOOPS ↓FUNCTIONS ↓FILES ↓PROCESSES ↓SERVICES ↓WINDOWS USERS ↓LOCAL GROUPS ↓EVENT LOGS ↓REGISTRY ↓ACTIVE DIRECTORY ↓SECURITY AUTOMATIONThe goal will be to use PowerShell as a practical tool for Windows security administration, Active Directory assessment, SOC operations, incident response, evidence collection, configuration review, and Microsoft-focused security automation.