Introduction to Bash Scripting

repository·main·Indexed 27 days ago

https://github.com/bobbyiliev/introduction-to-bash-scripting

An open-source educational resource and eBook for learning Bash scripting. It covers fundamental syntax—including variables, arguments, arrays, conditionals, loops, and functions—as well as practical automation tasks such as log parsing, working with JSON via jq, and interacting with the Cloudflare API.

Tokens
22.8K
Snippets
78
Records
163
Agent score
86%

What's inside introduction-to-bash-scripting

  1. Understand Bash Scripting basics

    main

    Bash (Bourne-Again SHell) is a Unix shell and command language used as the default command interpreter in most Linux systems. It can be used in two ways:

    1. Interactively: Directly in your terminal.
    2. As a scripting language: Writing scripts to automate repetitive workloads, such as environment setup or task automation.

    To write Bash scripts, you need a Unix terminal and a text editor (e.g., VS Code, Sublime Text, vim, or nano).

  2. Run the spike_check script to summarize access logs

    main
    To use the script, first make it executable using chmod +x. Then, execute the script by passing the path to your NGINX or Apache access log as the first argument. The script provides a summary including the top 20 pages with the most POST requests, the top 20 pages with the most GET requests, and the top 20 IP addresses with their geo-location.
  3. Add color to Bash output using variables and functions

    main

    To improve the readability of your Bash scripts, you can define ANSI escape code variables and wrap them in helper functions to apply colors to text easily.

    Color Variables

    Define these at the start of your script:

    • green='\e[32m'
    • blue='\e[34m'
    • red='\e[31m'
    • clear='\e[0m'

    Color Functions

    Create functions that take a string as an argument and wrap it in the desired color codes:

    ColorGreen(){
        echo -ne "${green}${1}${clear}"
    }
    
    ColorBlue(){
        echo -ne "${blue}${1}${clear}"
    }

    Usage

    Use command substitution to apply the color to a string:

    echo -ne "$(ColorBlue 'Some text here')"
    ColorGreen(){
    	echo -ne "${green}${1}${clear}"
    }
    
    echo -ne "$(ColorGreen 'Some text here')"
  4. Execute a BASH script on multiple remote servers

    main

    You can execute a local BASH script on multiple remote servers without manually copying the script to each machine or logging in individually. This is achieved by using a while loop to iterate through a list of server IP addresses and piping the local script into a remote bash -s command via SSH.

    Steps to execute:

    1. Create a file named servers.txt containing one server IP address (or hostname) per line.
    2. Prepare your local script (e.g., remote_check.sh).
    3. Run the following loop in your terminal to iterate through the list and execute the script on each server:
    while IFS= read -r server; do ssh "your_user@${server}" 'bash -s' < ./remote_check.sh ; done < servers.txt
  5. Define Bash functions

    main

    Bash functions allow you to reuse code blocks. You can define them using two syntaxes: including the function keyword or omitting it. Using the function keyword is recommended for better readability.

    Important: When calling a function, do not include parentheses ().

    # Syntax 1: With 'function' keyword (Recommended)
    function function_name() {
        your_commands
    }
    
    # Syntax 2: Without 'function' keyword
    function_name() {
        your_commands
    }
    
    # Calling the function (Do NOT use parentheses here)
    function_name
  6. Use switch case statements in Bash

    main

    The case statement simplifies complex conditional logic when comparing a single variable against multiple patterns.

    Syntax Rules:

    • Start with case $variable in.
    • Patterns end with a closing parenthesis ).
    • Multiple patterns can be combined using the pipe | operator.
    • Each clause must end with double semicolons ;;.
    • Use * as a default pattern to catch anything that doesn't match previous cases.
    • Close the statement with esac (case spelled backwards).

    Example of matching car brands to their manufacturing locations:

    #!/bin/bash
    
    read -p "Digite o nome da marca do seu carro: " carro
    
    case $carro in
    
      Tesla)
        echo -n "A fábrica de carros de ${carro} está nos EUA."
        ;;
    
      BMW | Mercedes | Audi | Porsche)
        echo -n "A fábrica de carros de ${carro} fica na Alemanha."
        ;;
    
      Toyota | Mazda | Mitsubishi | Subaru)
        echo -n "A fábrica de carros de ${carro} está no Japão."
        ;;
    
      *)
        echo -n "${carro} é uma marca de carro desconhecida"
        ;;
    
    esac
  7. Control loop execution with `continue` and `break`

    main

    You can control the flow of loops using continue and break:

    • continue [n]: Skips the remainder of the current iteration and starts the next one. The optional argument [n] specifies which nesting level of loops to continue (e.g., continue 2 continues the second surrounding loop). continue 1 is equivalent to continue.
    • break [n]: Terminates the loop immediately. The optional argument [n] specifies which nesting level of loops to exit. break 1 is equivalent to break. Use break 2 to exit a nested loop and the outer loop simultaneously.