Linux - Bash Scripting Basics

Bash scripting is one of the most essential skills for anyone working with Linux systems. Bash (Bourne Again Shell) allows you to automate tasks, simplify workflows, and run multiple commands efficiently using script files. Understanding the basics of Bash scripting gives you the foundation to build powerful automation tools and manage systems effectively.


1. What Is a Bash Script?

A Bash script is a text file containing a sequence of commands that the Bash shell executes. Instead of typing commands manually, you store them in a file and run the script to perform actions automatically.

A script typically starts with a shebang:

#!/bin/bash

This tells the system that the script should be run using the Bash interpreter.


2. Creating and Running a Bash Script

Step 1: Create a file

nano myscript.sh

Step 2: Add commands inside

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

Step 3: Save and give execute permission

chmod +x myscript.sh

Step 4: Run the script

./myscript.sh

3. Variables in Bash

Variables store data that you can reuse in your script.

Assigning a variable

name="Vidhisha"

Using a variable

echo "Hello, $name"

No spaces are allowed around the equal sign.


4. Taking Input from User

Use read to accept user input.

echo "Enter your name:"
read username
echo "Welcome, $username!"

5. Conditional Statements

Used to make decisions.

if [ $age -ge 18 ]; then
    echo "Adult"
else
    echo "Not an adult"
fi

6. Loops in Bash

Loops repeat a block of code.

For Loop

for i in 1 2 3 4 5
do
    echo "Number: $i"
done

While Loop

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

7. Functions in Bash

Functions group commands together for reuse.

greet() {
    echo "Hello from the function!"
}

greet

8. Passing Arguments to Scripts

Arguments are accessed using $1, $2, etc.

#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"

Run:

./script.sh apple banana

9. Command Substitution

Store output of a command inside a variable.

today=$(date)
echo "Today is: $today"

10. Comments in Bash

Use # to write comments.

# This is a comment
echo "This line runs"

Why Bash Scripting Is Important?

  • Automates repetitive tasks

  • Saves time and reduces errors

  • Helps in system administration

  • Useful for DevOps, cloud, and server management

  • Enhances productivity


 

In summary, Bash scripting basics include understanding variables, loops, conditions, functions, input handling, and script execution. Mastering these fundamentals enables you to automate tasks and become more efficient in Linux environments.