CoDeKu DevOps Academy Blog - DevOps & Cloud Blogging Platform

Bash Scripting Basics: Automate Your Linux Tasks

Have you ever repeated the same Linux commands over and over and thought, “There must be an easier way” 🤔 That’s where Bash scripting comes in! Whether you’re a beginner trying to automate small tasks or an aspiring sysadmin, learning how to write Bash scripts will level up your Linux skills🚀

Real-Time Use Cases of Bash Scripting

  • 🔁 Automation of Repetitive Tasks: Bash scripts are commonly used to automate repetitive tasks such as file backups, log rotation, and software updates. This reduces manual effort and minimizes the risk of human error.
  • 💻 System Administration: System administrators rely on Bash scripts for tasks like user management, system monitoring, and server maintenance.
  • ⚙️ Software Installation and Configuration: Bash scripts can streamline the process of installing and configuring software packages, especially in environments with multiple servers or virtual machines.
  • 📁 File Management: Bash scripts can automate file operations such as renaming, moving, and deleting files. They are also useful for processing and manipulating text files for data extraction and transformation.
What is a Bash Script📜
A Bash script is a plain text file containing a set of commands written for the Bash (Bourne Again SHell) interpreter on Linux or Unix-based systems. These scripts automate actions that would ordinarily be done manually in the terminal. Bash scripts can include system commands, utilities, logic (such as loops and conditionals), and functions, making them a powerful tool for system administrators, developers, and anyone working in a Unix/Linux environment.
Key Features of Bash Scripts:
    🔹 Bash scripts file extension is .sh (e.g., myscript.sh).

    🔹 Starts with #!/bin/bash (called a shebang) command on top of the script that tells the system to use Bash to execute the file.

    🔹 Before executing the script, you need to allow execution permission of that script using: chmod +x script.sh.

Bash Script
Creating and Running First Bash Script on Linux
🔷 Open the Linux terminal and use a text editor (like nano, vim, or echo) to create a new file, e.g., myscript.sh.
Creating a Bash Script
🔷 Add the shebang #!/bin/bash at the top, followed by commands like: echo "Hello, world!"
Adding Shebang

(If you are using the Nano editor, after adding your commands, press Ctrl + X, then Y to save, and press Enter.)

🔷 Use the chmod command to add execute permissions for the user and execute the script by typing its path (prefixed with ./ if it’s in the current directory).
Executing Script
Referencing Variables in Bash 📌
In this section, we discuss how to use variables, comments, and basic aspects of variable handling in Bash scripting.

Types of Variables:

  • User-Defined Variables: Created by the user to store custom values.
  • Pre-Defined Variables: Built-in variables predefined by the Linux system, written in uppercase.
User define variables:
myname="Jude"
echo "My name is $myname"
# Output: My name is Jude
Deleting Local Branch
Pre define variables:
echo "Our shell name is $BASH"
# Output: Our shell name is /bin/bash

echo "Our shell version is $BASH_VERSION"
# Output: Our shell version is 5.x.x
Comments in Bash Scripts:
To add comments, use the # symbol. Anything following it on the same line is ignored by the interpreter.
Deleting Local Branch
Getting User Input in Bash 💻

The read command in Bash facilitates obtaining user input during script execution. It reads a line from standard input and assigns it to a variable.

Example of Read Command

To get multiple user inputs:

        echo "Enter names: "
        read name1 name2 name3
        echo "Names: $name1, $name2, $name3"
      

Special Feature: Password Input

A unique feature in Bash is obtaining a password as user input. When the user types their password, it will not display on the screen, ensuring security. Once entered, it can be used securely in the script.

You can also get user inputs from an array:

Getting Inputs from Array
Conditional Statements in Bash 🧩

Conditional statements like if, elif, and else allow you to control the flow of a Bash script based on conditions. These commands are fundamental for scripting logic.

Example: If-Else Statement

If-Else Example

Example: If-Elif-Else Statement

If-Elif-Else Example
Loops in Bash 🔄

Loops in Bash scripting are control structures that facilitate the repeated execution of a block of code. Bash provides three primary types of loops:

For Loop

Iterates over a sequence of items, such as a list of files, numbers, or strings.

Example of a Bash Function

While Loop

Executes a block of code as long as a specified condition is true.

Example of a Bash Function

Until Loop

Executes a block of code as long as a specified condition is false.

Example of a Bash Function

Case Statement 🌀

The case statement in Bash is a control flow structure that allows for selecting one block of code from multiple choices. It is similar to a switch statement in other programming languages. This structure is a cleaner alternative to using multiple if-elif-else statements, especially when managing a variety of possible values.


Example of a Bash Function


The script prompts the user to enter a number (1, 2, or 3). It then uses a case statement to evaluate the input and execute the corresponding block of code. If the input doesn’t match any of the defined options, it outputs an “Invalid choice” message.

✅ This approach provides a more readable and maintainable way to handle multiple conditions in Bash scripts.

Functions in Bash Scripting 🛠️

In Bash scripting, functions help you group a set of commands and reuse them wherever needed. This approach makes your scripts cleaner, more organized, and easier to manage.

Defining a Bash Function

The syntax for defining a Bash function is as follows:


function_name() {
  # Commands go here
}
    
Example of function :
Example of a Bash Function

In this simple Bash script, A function called say_hello that takes one input and prints a greeting message. The function is then called twice with different arguments: “Sasanka” and “World”. When executed, the script outputs “Hello, Sasanka!” followed by “Hello, World!”

Returning Values From Functions:

Bash functions don’t return values like other programming languages — but you can use echo to output a value and capture it with command substitution.

Example of a Bash Function

🏁 Conclusion

Bash scripting is a powerful tool that lets you automate tasks, manage systems, and boost your productivity in a Linux environment. In this guide, we explored the basics — from printing messages 📝 and reading user input to using loops and creating functions.

🌱 If you’re just getting started, keep experimenting with simple scripts. As you get more comfortable, you’ll discover how Bash can help streamline daily tasks and even solve complex problems with just a few lines of code.


Happy scripting — and welcome to the world of Linux automation! 🐧💻

Share This Article

Sasanka Ranawaka
Sasanka Ranawaka

I'm an undergraduate at the University of Sri Jayewardenepura, passionate about technology, coding, and cybersecurity. I enjoy working on software projects, networking setups, and machine learning models. With experience in languages like Java, Python, C#, and full-stack development (MERN), I’m always exploring new ways to solve problems and grow in the tech field.

Articles: 3

Leave a Reply

Your email address will not be published. Required fields are marked *