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 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.

    Continue Learning

    Linux · Intermediate

    Linux Terminal Guide: Advanced Shell Skills for Professionals

    Advanced Linux terminal techniques including shell customization, multiplexing, productivity tools, and scripting best practices.

    Linux · Beginner

    Command Line Essentials: Mastering the Terminal for Security Work

    Essential command line skills for cybersecurity professionals including navigation, text processing, scripting, and automation.

    Linux · Beginner

    Linux Process Management: Monitoring and Controlling Processes

    Learn to manage Linux processes effectively including monitoring tools, signals, priority control, background jobs, and automation with systemd.

    Linux · Beginner

    100 Essential Linux Commands Every Beginner Should Know

    A quick-reference cheat sheet of 100 essential Linux commands every beginner should know, organized by category with syntax, examples, and practical use cases for system administration and cybersecurity.

    Related Security Tools

    Information Gathering

    SMBClient

    Learn how to use SMBClient on Kali Linux: install Samba's FTP-like SMB/CIFS client, list shares, connect as a guest or with credentials, browse folders, and upload or download files on Windows, Samba, or NAS devices. For authorized assessments, check ports 139/445 with Nmap before testing share permissions.

    Reverse Engineering

    ADB

    ADB, or Android Debug Bridge, is a versatile command-line tool that acts as a client-server program, facilitating communication between your development machine (the client) and an Android device (running the adbd daemon) via a server process binding TCP port 5037. It ships as part of the Android SDK Platform Tools, and on Kali Linux, it's available as the `android-tools-adb` package. ADB is the standard device bridge for Android mobile pentesting and forensics, enabling actions like deploying Frida servers, pulling APKs, and capturing detailed logcat output for analysis.

    Web Application

    Commix

    Commix (Command Injection Exploiter) is an automated tool designed to test, detect, and exploit command injection vulnerabilities in web applications, facilitating automated OS shell access.

    Reverse Engineering

    GDB

    Learn how to use GDB, the GNU Debugger, by building a small C program with debug symbols and following it from the first breakpoint to a crash. Use the same steps to inspect variables, read a backtrace, and tell when a core dump or a look at the assembly would help.

    Practice Linux Skills

    Command reference

    Linux Commands Reference

    Browse 163 practical Linux and Kali terminal commands.

    Interactive practice

    Terminal Sandbox

    Practice common Linux commands safely in your browser.

    Written by GO KALI FREE Team