DEV Community

Cover image for Become a Bash Scripting Pro in 10 Minutes: A Quick Guide for Beginners
Mohammad Imran
Mohammad Imran

Posted on

Become a Bash Scripting Pro in 10 Minutes: A Quick Guide for Beginners

Bash scripting is a powerful tool that every developer, DevOps engineer, or system administrator should have in their toolkit. It allows you to automate repetitive tasks, manage systems, and build custom workflows—all from the command line. If you’re new to bash scripting, don’t worry! This guide will help you grasp the basics in just 10 minutes.


What is Bash?

Bash (Bourne Again SHell) is a command-line interpreter and scripting language used in Linux and macOS environments. It provides a way to interact with the operating system and automate tasks by writing scripts.


Getting Started: Hello, World!

  1. Open Your Terminal: Bash scripts are written and executed in the terminal.

  2. Create a Script File:

    nano hello.sh
    

    Replace nano with your preferred editor.

  3. Write Your First Script:

    #!/bin/bash
    echo "Hello, World!"
    
* `#!/bin/bash` tells the system to use Bash for interpreting the script.

* `echo` prints the text to the terminal.
Enter fullscreen mode Exit fullscreen mode
  1. Make It Executable:

    chmod +x hello.sh
    
  2. Run the Script:

    ./hello.sh
    

Congratulations! You’ve written and executed your first bash script.


Beginner-Friendly Real-World Examples

1. Creating a Reminder

Description: This script reminds you to take a break every hour by printing a message. It uses the sleep command to pause execution for 3600 seconds (1 hour).

Script:

#!/bin/bash

while true; do
    echo "Remember to take a break!"
    sleep 3600
done
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • The while true loop ensures the script runs indefinitely, continuously reminding you to take breaks.

  • echo "Remember to take a break!" prints the message to the terminal.

  • sleep 3600 pauses the script for 3600 seconds (1 hour) before displaying the message again.


2. Batch Renaming Files

Description: This script appends the current date to all .txt files in the current directory, helping organize files more systematically.

Script:

#!/bin/bash

date=$(date +%Y-%m-%d)
for file in *.txt; do
    mv "$file" "${file%.txt}-$date.txt"
done

echo "Files renamed successfully."
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • date=$(date +%Y-%m-%d) captures the current date in the format YYYY-MM-DD and assigns it to the variable date.

  • for file in *.txt iterates over every file in the directory with a .txt extension.

  • mv "$file" "${file%.txt}-$date.txt" renames each file by appending the date to its name. ${file%.txt} removes the .txt extension before appending the date.

  • The echo statement confirms that the renaming process is complete.


3. Basic Calculator

Description: This script performs basic addition and multiplication of two numbers provided by the user.

Script:

#!/bin/bash

echo "Enter first number:"
read num1
echo "Enter second number:"
read num2

sum=$((num1 + num2))
product=$((num1 * num2))

echo "Sum: $sum"
echo "Product: $product"
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • echo "Enter first number:" prompts the user to input the first number.

  • read num1 stores the input in the variable num1.

  • echo "Enter second number:" prompts the user to input the second number.

  • read num2 stores the input in the variable num2.

  • $((num1 + num2)) performs addition, and $((num1 * num2)) performs multiplication.

  • echo prints the results of the calculations, displaying the sum and product.


4. Directory Organizer

Description: This script organizes files into folders based on their types, such as images, documents, and others.

Script:

#!/bin/bash

mkdir -p images documents others

for file in *; do
    if [[ $file == *.jpg || $file == *.png ]]; then
        mv "$file" images/
    elif [[ $file == *.pdf || $file == *.docx ]]; then
        mv "$file" documents/
    else
        mv "$file" others/
    fi
done

echo "Files organized into categories."
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • mkdir -p images documents others creates folders named images, documents, and others if they don't already exist.

  • for file in * iterates through all files in the current directory.

  • The if-elif structure checks the file extensions to determine their type:

    • Files with .jpg or .png extensions are moved to the images folder.
    • Files with .pdf or .docx extensions are moved to the documents folder.
    • All other files are moved to the others folder.
  • mv "$file" <folder>/ moves each file into the appropriate folder.

  • The echo statement confirms that the files have been organized.


5. Greeting Based on Time

Description: This script greets users based on the current time of day, providing a personalized experience.

Script:

#!/bin/bash

hour=$(date +%H)
if [ $hour -lt 12 ]; then
    echo "Good morning!"
elif [ $hour -lt 18 ]; then
    echo "Good afternoon!"
else
    echo "Good evening!"
fi
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • date +%H retrieves the current hour (in 24-hour format) and assigns it to the variable hour.

  • The if-elif structure checks the value of hour:

    • If the hour is less than 12, it prints "Good morning!"
    • If the hour is between 12 and 18, it prints "Good afternoon!"
    • Otherwise, it prints "Good evening!"

6. Weekly Planner

Description: This script creates a text file with placeholders for tasks for each day of the workweek.

Script:

#!/bin/bash

for day in Monday Tuesday Wednesday Thursday Friday; do
    echo "$day: " >> weekly_planner.txt
done

echo "Weekly planner created."
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation:

  • for day in Monday Tuesday Wednesday Thursday Friday iterates over the names of the weekdays.

  • echo "$day: " >> weekly_planner.txt appends each weekday followed by a colon to the file weekly_planner.txt. If the file does not exist, it is created.

  • After the loop completes, echo "Weekly planner created." confirms the planner's creation.


Quick Tips for Writing Scripts

  1. Add Comments: Use # to describe what your script does.

    # This script prints a greeting
    echo "Hello, World!"
    
  2. Debugging: Run your script with bash -x script.sh to debug.

  3. Exit Codes: Use exit to return specific codes after execution.

    exit 0 # Success
    exit 1 # Error
    

Wrap Up

Bash scripting is a foundational skill that can significantly boost your productivity. With just a few commands and a basic understanding of the syntax, you can start automating tasks today. The examples here are just the beginning—keep practicing, experimenting, and building scripts to unlock the full potential of bash!


Are you ready to master bash scripting? Share your first script or favorite bash trick in the comments! 🚀

Top comments (0)