Bash Scripting for Beginners: A Step-by-Step Tutorial

Welcome to the world of Bash scripting! This tutorial is designed for new users who want to learn how to automate tasks using Bash, the command-line shell used in most Linux and macOS systems. Bash is a powerful tool that can help you streamline repetitive tasks and manage your system more efficiently.

What is Bash?

Bash (Bourne-Again Shell) is a command-line interpreter that allows you to interact with your operating system. It's used for:

Getting Started with Bash

Step 1: Open Terminal

On Linux: Use your terminal (e.g., GNOME Terminal, Konsole, etc.) On macOS: Open "Terminal" from Applications On Windows 10/11: Use "Windows Terminal" or "PowerShell" (Bash is pre-installed)

Step 2: Your First Bash Command

Open your terminal and type:

echo "Hello, World!"

Press Enter. You should see:

Hello, World!

This is your first Bash command! echo is a built-in command that prints text to the screen.

Basic Bash Syntax

1. Variables

In Bash, you can store values in variables without declaring their type.

name="Alice"
echo "Hello, $name!"

Output:

Hello, Alice!

2. Commands

You can run any command in Bash, like ls (list files), cd (change directory), mkdir (make directory), etc.

ls
cd Desktop
mkdir my_folder

Using Loops

For Loop

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

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

While Loop

count=0
while [ $count -lt 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

File and Directory Operations

Basic Arithmetic

You can perform arithmetic operations in Bash using $((...)):

a=10
b=5
echo "Addition: $((a + b))"
echo "Subtraction: $((a - b))"
echo "Multiplication: $((a * b))"
echo "Division: $((a / b))"

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2

Comments

You can add comments to your script using #:

# This is a comment
echo "This line is executed"

Writing a Bash Script

Step 1: Create a Script File

nano hello_script.sh

Step 2: Add the Shebang Line

The shebang line tells the system which interpreter to use:

#!/bin/bash
echo "Hello, World!"

Step 3: Make the Script Executable

chmod +x hello_script.sh

Step 4: Run the Script

./hello_script.sh

Output:

Hello, World!

Practice Exercises

Try these simple exercises to reinforce your learning:

I wrote a flashcard game in python for learning bash commands, you can download it here.

Once you download it use this command to start it: python3 bashcommands.py

Next Steps

Now that you've learned the basics, you can explore:

Resources

You're Now a Bash Scripting Developer!

You've taken your first steps into the world of Bash scripting. Keep practicing, and you'll be amazed at what you can build with Bash! If you have any questions or need help with anything, feel free to ask!

Happy scripting!