Developer Guides

Bash Script Tutorial: Fundamental Concepts and File Operations

Explore the fundamentals of bash scripting, including variables, functions, loops, and file operations, with practical examples.

5 min read

Explore the foundational concepts of bash scripting, including variables, loops, conditions, functions, and file operations. This comprehensive guide provides practical examples to help you get started with creating your own scripts, automating repetitive tasks, and managing files and directories efficiently using bash scripting.

Introduction to Bash Scripting

Bash (Bourne Again Shell) scripting is a powerful way to automate tasks, execute commands sequentially, and streamline operations on Linux or Unix systems. Often used for system management, CI/CD pipelines, and server automation, bash scripts enable developers and system administrators to optimize workflows and ensure consistency.

This tutorial will guide you step-by-step on the fundamental concepts of bash scripting, highlighting how to manage variables, loops, conditionals, functions, and file operations.


Understanding Bash and Shell

A shell is an interface used to execute commands from the operating system. Bash (short for Bourne Again Shell) is one of the most popular shells available. Bash scripts are typically saved with the .sh file extension. We'll be using bash throughout this tutorial.


Creating Your First Bash Script

Let's create and run a basic bash script.

Example:

We'll create a script that prints "Hello, World!"

steps

  1. Open your terminal and navigate to your desired directory.

  2. Create a script file using a text editor, e.g., nano hello_world.sh.

  3. Write the following bash script into the file:

    bash
    #!/bin/bash
    echo "Hello, World!"
  4. Save and exit the file.

  5. Make the script executable:

bash
    chmod +x hello_world.sh
  1. Run the script:
bash
    ./hello_world.sh
    # Output: Hello, World!

Using Variables in Bash Scripts

Variables are containers for storing data and can simplify your script by allowing easy configuration and reuse.

Example:

Create a script to demonstrate variables and perform basic arithmetic.

bash
#!/bin/bash

# Define variables
num1=10
num2=5

# Perform arithmetic
sum=$((num1 + num2))
diff=$((num1 - num2))
prod=$((num1 * num2))
quot=$((num1 / num2))

# Display the results
echo "Sum: $sum"
echo "Difference: $diff"
echo "Product: $prod"
echo "Quotient: $quot"

Output Example:

Sum: 15
Difference: 5
Product: 50
Quotient: 2

Adding Logic with Conditions

Use if, elif, and else statements to introduce decision-making capabilities to your bash scripts.

Example:

Script to check if a number is positive, negative, or zero.

bash
#!/bin/bash

read -p "Enter a number: " num

if [ $num -gt 0 ]; then
  echo "The number is positive."
elif [ $num -lt 0 ]; then
  echo "The number is negative."
else
  echo "The number is zero."
fi

Usage:

Running the condition-check script

./check_number.sh
# Enter a number: 10
# Output: The number is positive.

Building Dynamic Scripts with Functions

Functions enable reuse of code blocks and make your scripts modular.

Example:

Creating a reusable function to calculate the factorial of a number.

bash
#!/bin/bash

# Define the factorial function
function factorial {
  local num=$1
  result=1
  for (( i=1; i<=num; i++ )); do
    result=$((result * i))
  done
  echo $result
}

# Prompt user for input
read -p "Enter a number to calculate its factorial: " number

# Call the function
factorial_result=$(factorial $number)
echo "Factorial of $number is: $factorial_result"

Output Example:

Enter a number to calculate its factorial: 5
Factorial of 5 is: 120

Automation Example: File Creation Script

This example demonstrates the creation of multiple numbered files using a for loop.

bash
#!/bin/bash

# Prompt for filename prefix
read -p "Enter file prefix: " prefix
read -p "Enter the number of files to create: " num_files

# Create the specified number of files
for ((i=1; i<=num_files; i++)); do
  touch "${prefix}_${i}.txt"
  echo "Created file: ${prefix}_${i}.txt"
done

Example Usage:

Running file creation script

./file_creation.sh
# Enter file prefix: file
# Enter the number of files to create: 3
# Created file: file_1.txt
# Created file: file_2.txt
# Created file: file_3.txt

Cloning a GitHub Repository Using Bash

Learn how to automate cloning a GitHub repository using bash scripting.

Example:

We will prompt the user to input a repository URL, verify it for correctness, and clone it.

bash
#!/bin/bash

# Prompt for repository URL
read -p "Enter the repository URL: " repo_url

# Validate repository URL
if [[ $repo_url == *"github.com"* ]]; then
  echo "Cloning repository..."
  git clone "$repo_url"
  
  if [ $? -eq 0 ]; then
    echo "Repository cloned successfully."
  else
    echo "Failed to clone repository."
  fi
else
  echo "Invalid repository URL. Please enter a GitHub repository URL."
fi

Usage Example:

Cloning a GitHub repository

./clone_repo.sh
# Enter the repository URL: https://github.com/example_repo.git
# Output: Cloning repository...
# Repository cloned successfully.

FAQ

What is Bash scripting used for?

Bash scripting is commonly used for automating system tasks, managing servers, and executing a series of commands efficiently. With concepts like variables, loops, and functions, it allows for streamlined workflows and reduced manual effort for sysadmins and developers.

How do I run a Bash script?

Save your script with a .sh extension, make it executable using chmod +x filename.sh, and run the script in the terminal with ./filename.sh.

How do I create multiple files in Bash?

To create multiple files in a loop, use a for loop along with the touch command. You can create numbered files based on a prefix or customized user input.

How do I validate user input in Bash scripts?

You can validate user input using conditional statements. For example, with if statements and regular expressions, you can ensure inputs are in the correct format or match a specific pattern.


Official reference: GNU Bash manual.