Introduction Bash Scripting Tutorial

Definition of Bash scripting

Bash scripting allows you to automate tasks and create custom command-line tools using the Bash shell. Here are some essential Bash scripting commands and concepts for working with the command line:

  1. Shebang:

    • Start your Bash script with a shebang (#!/bin/bash) to specify the Bash interpreter.
    bashCopy code#!/bin/bash
  1. Comments:

    • Use # to add comments for documentation within your script.
    bashCopy code# This is a comment
  1. Variables:

    • Create and use variables to store and manipulate data.
    bashCopy codemy_var="Hello, World!"
    echo $my_var
  1. User Input:

    • Read user input using the read command.
    bashCopy codeecho "Enter your name:"
    read user_name
    echo "Hello, $user_name!"
  1. Conditionals (if-then-else):

    • Use conditional statements to make decisions in your script.
    bashCopy codeif [ "$user_name" == "Alice" ]; then
        echo "Hello, Alice!"
    elif [ "$user_name" == "Bob" ]; then
        echo "Hello, Bob!"
    else
        echo "Hello, stranger!"
    fi
  1. Loops (for and while):

    • Implement loops for repetitive tasks.
    bashCopy codefor i in {1..5}; do
        echo "Iteration $i"
    done

    counter=1
    while [ $counter -le 5 ]; do
        echo "Iteration $counter"
        ((counter++))
    done
  1. Functions:

    • Define functions to encapsulate and reuse code.
    bashCopy codegreet() {
        local name="$1"
        echo "Hello, $name!"
    }

    greet "Alice"
  1. Command Substitution:

    • Capture command output using $().
    bashCopy codecurrent_date=$(date +%Y-%m-%d)
    echo "Today is $current_date"
  1. Error Handling:

    • Check for errors and handle them.
    bashCopy codeset -e  # Exit on error

    if [ ! -f my_file.txt ]; then
        echo "File not found!"
        exit 1
    fi
  1. File Operations:

    • Perform file-related tasks such as creation, reading, and deletion.
    bashCopy code# Create a file
    touch my_file.txt

    # Read a file
    cat my_file.txt

    # Delete a file
    rm my_file.txt
  1. Script Execution:

    • Make your script executable with chmod and execute it.
    bashCopy codechmod +x my_script.sh
    ./my_script.sh

These are some key Bash scripting commands and concepts for working with the command line. You can combine and expand upon these elements to create more complex scripts for various automation tasks and system administration. Additionally, you can explore the Bash manual (man bash) for more in-depth information on Bash scripting features and syntax.

Did you find this article valuable?

Support Rajat Shrestha by becoming a sponsor. Any amount is appreciated!