GO KALI FREE
BeginnerLinux

Bash Scripting Basics: Automate Tasks Like a Pro

Learn Bash scripting from scratch covering variables, conditionals, loops, functions, error handling, and practical automation scripts for cybersecurity.

#Bash#shell scripting#automation#Linux#scripting

Why Learn Bash Scripting?

Bash scripting automates repetitive tasks on Linux. Instead of typing commands manually, scripts execute sequences automatically. For cybersecurity, Bash scripting automates reconnaissance, log analysis, tool execution, and reporting.

Prerequisites

Basic Linux commands (ls,cd, grep, awk, sed), terminal navigation, and a text editor.

Script Structure

Every script starts with a shebang and can include comments:

#!/bin/bash
# This is a comment
echo "Hello, World!"

Making Scripts Executable

chmod +x script.sh
./script.sh

Variables

#!/bin/bash
name="KaliGo"
echo "Hello, $name!"
current_date=$(date)
echo "Today is: $current_date"
count=$((5 * 10))
echo "Result: $count"

Arrays

tools=("nmap" "wireshark" "metasploit")
echo ${tools[0]}         # nmap
echo ${tools[@]}         # All elements
echo ${#tools[@]}        # Array length

User Input

read -p "Enter target IP: " target
echo "Scanning $target..."
read -s -p "Enter password: " password

Conditionals

if [ "$num" -gt 10 ]; then
    echo "Greater than 10"
elif [ "$num" -eq 10 ]; then
    echo "Exactly 10"
else
    echo "Less than 10"
fi

File Tests

if [ -f "$file" ]; then echo "File exists"; fi
if [ -d "$dir" ]; then echo "Directory exists"; fi
if [ -x "$file" ]; then echo "File is executable"; fi

Loops

# For loop
for tool in nmap wireshark metasploit; do
    echo "Tool: $tool"
done

# Number range
for i in {1..5}; do
    echo "Iteration: $i"
done

# While loop
count=1
while [ "$count" -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

# Read file line by line
while IFS= read -r line; do
    echo "Line: $line"
done < targets.txt

Functions

scan_port() {
    local host=$1
    local port=$2
    nc -zv "$host" "$port" 2>/dev/null
    if [ $? -eq 0 ]; then
        echo "Port $port is OPEN on $host"
    else
        echo "Port $port is CLOSED on $host"
    fi
}
scan_port "192.168.1.1" 80

Error Handling

set -euo pipefail    # Exit on error, undefined vars, pipe failures

Practical Automation

Network Scan Script

#!/bin/bash
set -euo pipefail
TARGET="$1"
OUTPUT_DIR="scan_results"
mkdir -p "$OUTPUT_DIR"
nmap -sn "$TARGET" -oG "$OUTPUT_DIR/ping_scan.txt"
nmap -sV -sC "$TARGET" -oN "$OUTPUT_DIR/port_scan.txt"
nmap --script vuln "$TARGET" -oN "$OUTPUT_DIR/vuln_scan.txt"
echo "Scan complete. Check $OUTPUT_DIR."

Log Analysis Script

#!/bin/bash
LOG_FILE="/var/log/auth.log"
echo "=== SSH Failed Logins ==="
grep "Failed password" "$LOG_FILE" | awk '{print $1, $2, $11}' | sort | uniq -c | sort -rn | head -10

Real-World Examples

Automated reconnaissance running theHarvester, DNS enumeration, and Nmap. Backup automation with cron. Phishing URL checker against multiple APIs.

Common Mistakes

Missing shebang, spaces in variable assignment (name = "value" is wrong), not quoting variables, not checking exit codes.

Best Practices

Use set -euo pipefail. Quote all variable expansions. Use meaningful names. Validate input. Handle errors gracefully. Use trap for cleanup. Lint with shellcheck.

Related Tools

shellcheck — Static analysis. bashdb — Debugger. shfmt — Formatter. expect — Interactive automation. parallel — Execute in parallel.

Related Articles

  • command-line-essentials
  • linux-commands-explained
  • linux-terminal-guide
  • linux-file-permissions
  • kali-linux-beginner-guide
  • Summary

    Bash scripting automates tasks using variables, conditionals, loops, functions, and error handling. Key practices: shebang line, proper quoting, exit codes ($?), and set -euo pipefail. Practical uses include automated scanning, log analysis, and tool orchestration.

    Knowledge Check

  • What does the shebang `#!/bin/bash` do?
  • How do you make a script executable?
  • What does `set -euo pipefail` do?
  • How do you capture command output into a variable?
  • What is `$?` in a Bash script?
  • Frequently Asked Questions

    What is the difference between a shell script and a Bash script?

    A shell script is any script written for a shell interpreter, while a Bash script specifically uses Bash features. The shebang #!/bin/bash ensures Bash is used. Bash scripts can use arrays, [[ ]] conditionals, and other Bash-specific syntax not available in POSIX sh. See our [command line guide](/learn/command-line-essentials) for shell basics.

    How do I pass arguments to a Bash script?

    Use positional parameters: $1 for the first argument, $2 for the second, $@ for all arguments, and $# for the argument count. Example: `./scan.sh 192.168.1.1` sets $1 to 192.168.1.1. Always quote variables ("$1") to handle arguments with spaces correctly.

    What does set -euo pipefail do and why is it essential?

    set -e exits on error, set -u treats undefined variables as errors, and set -o pipefail propagates failures through pipe chains. Together they prevent silent failures that can corrupt data or leave systems in bad states. Add this after the shebang in every script.

    How do I read user input in a Bash script?

    Use `read -p 'Prompt: ' variable` for text input and `read -s -p 'Password: ' pass` for hidden input. The -p flag shows a prompt, -s hides keystrokes, and -n limits characters. Always validate input before using it in commands to prevent injection.

    What is the difference between $@ and $* when quoted?

    "$@" expands each argument as a separate word, while "$*" joins all arguments into a single string. Use "$@" in for loops to iterate over arguments correctly, and "$*" when you want to concatenate them. This distinction matters when arguments contain spaces.

    How do I create a simple automation script for Nmap scanning?

    Write a script that takes a target IP as $1, creates an output directory with mkdir -p, then runs nmap -sn for host discovery, nmap -sV -sC for services, and nmap --script vuln for vulnerabilities. Use set -euo pipefail for error handling and redirect output to dated files.

    How do I debug a Bash script that isn't working?

    Run with `bash -x script.sh` to print each command before execution. Add `set -x` inside the script to toggle debug output. Use `echo` statements to print variable values. Install shellcheck with `sudo apt install shellcheck` to catch common errors statically.

    What is the trap command used for in scripts?

    trap catches system signals and runs cleanup code. Use `trap 'rm -f /tmp/lock' EXIT` to remove temp files on exit, or `trap 'exit' INT` to handle Ctrl+C gracefully. Essential for scripts that create temporary files, lock resources, or modify system state.

    How do I schedule a Bash script to run automatically?

    Use cron for time-based scheduling: `crontab -e` then add `0 2 * * * /path/script.sh` for daily 2 AM execution. For event-based triggers, use systemd timers. Combine with logging (`>> /var/log/script.log 2>&1`) to track automated execution.

    How do I make my Bash script handle errors gracefully?

    Use `set -euo pipefail` for basic error handling, check exit codes with `command || { echo error; exit 1; }`, and use trap for cleanup. For critical operations, validate inputs first and use if/else blocks around commands that might fail, providing meaningful error messages.

    What is the difference between > and >> in Bash?

    > overwrites the target file with new output, while >> appends to the end of the file. Use > when creating new log files and >> when adding to existing ones. Be careful: > destroys existing content. Combine with tee to both display and save output simultaneously.

    How do I use arrays in Bash scripts?

    Declare arrays with `arr=("nmap" "wireshark" "metasploit")`, access elements with `${arr[0]}`, get all elements with `${arr[@]}`, and count elements with `${#arr[@]}`. Use `for item in ${arr[@]} do ... done` to iterate. Arrays are zero-indexed and support dynamic resizing.