Writing your first Bash script: Best practices and examples

Leandro Padula

Share this article

Introduction

A few weeks ago, we embarked on an article discussing the importance of learning Bash for programmers, aiming to create a series of articles that would enable programmers to delve into Bash while adhering to best practices. We recognized the significant amount of information available that often neglects these essential guidelines.

This article, specifically tailored for programmers, aims to guide them in creating their initial scripts while emphasizing the significance of following best practices.

First Steps into Bash

If you’re a programmer looking to automate tasks or manage system configurations, then learning how to write Bash scripts can be an incredibly powerful tool. Bash is a command-line shell and scripting language that is used in Linux, macOS, and other Unix-based operating systems. In this blog post, we’ll provide you with a step-by-step guide on how to write your first Bash script, along with an example.

Step 0: Choose Your Text Editor

Before we dive into writing our first Bash script, we need to choose a text editor. You can use any text editor that you’re comfortable with, but we recommend using Visual Studio Code.

For detailed information on the recommended extensions and their corresponding settings for Visual Studio Code, please refer to the following article: gauchocode.com/why-learn-bash

Step 1: Create our first Script

There is no better way to learn than by practicing, so the first step will be to create the foundation of our Bash script and then gradually test and execute code on it as needed.

Open your text editor and create a new file

We’ll call this file “myscript.sh“. The “.sh” extension indicates that this is a Bash script.

Add Shebang

The first line of a Bash script should always start with a shebang. The shebang tells the system which interpreter to use to run the script. Add the following line at the beginning of your script:

!/bin/bash

Print something

Now that we have our file set up, it’s time to write a simple script that greets the user:

!/bin/bash

echo "Welcome to my first Bash script!"

Step 2: Save and Execute Our Script

Save the script and make it executable by running the following command in your terminal:

chmod +x myscript.sh

This command makes the file executable. Now, we can run our script by typing the following command:

./myscript.sh

You should see the following output in your terminal:

Welcome to my first Bash script!

Step 3: Learn Bash basics with good practices

In this step, I will explain some concepts of Bash scripting with good practices, which you can test in the recently created script to evaluate the output.

Variables

  • Variables should always be referred to in the ${var} form as opposed to $var
  • Variables should always be quoted, especially if their value may contain a whitespace or separator character: "${var}"
# Correct
greeting="Hello, World!"
echo "${greeting}"  # Output: Hello, World!

# Incorrect
greeting=Hello, World!
echo $greeting 
Capitalization
  • Environment (exported) variables: ${ALL_CAPS}
  • Local variables: ${lower_case}
Prefer local variables within functions over global variables

If you need global variables, make them readonly:

readonly GLOBAL_VAR="Initial value"

GLOBAL_VAR="New value"  # This will generate an error

Arrays

Here are some good practices for working with arrays in Bash:

# Explicitly declare arrays to enhance code clarity and prevent unexpected behavior
my_array=()

# Initialize an array 
my_array=(1 2 3)  

# Retrieve third element 
${my_array[2]}

# Retrieve all elements 
${my_array[@]} 

# Retrieve array indices 
${!my_array[@]} 

# Calculate array size 
${#my_array[@]} 

# Overwrite 1st element 
my_array[0]=3

# Append value(s) 
my_array+=(4) 

# Save ls output as an array of files 
my_array=( $(ls) )

# Retrieve n elements starting at index s
${my_array[@]:s:n}

# Remove an element from an array
unset my_array[2]

# Iterate over array elements
for element in "${my_array[@]}"; do
    echo "${element}"
done

# Check if an array is empty
if [[ ${#my_array[@]} -eq 0 ]]; then
    echo "Array is empty"
fi

Always use long parameter notation when available

Long notation makes the script more readable, especially for lesser known/used commands that you don’t remember all the options for.

# Good:
rm --recursive --force -- "${dir}"

# Avoid:
rm -rf -- "${dir}"

Making your scripts more robust and error-resistant with exit and return

exit

Use exit codes ($?) to indicate the success or failure of the script. Conventionally, an exit code of 0 indicates success, while any non-zero value represents an error or failure.

Provide meaningful error messages when exiting due to an error, making it easier to diagnose and troubleshoot issues.

# Exiting with an error message
if [[ ! -f "${file}" ]]; then
    echo "Error: File not found!"
    exit 1
fi
return

Use the return statement to indicate the success or failure of a function by returning an exit code. Similar to the exit command, conventionally, an exit code of 0 represents success, while non-zero values represent errors.

# Using return within a function and an if statement
function my_function() {
    if [[ "${var}" = "value" ]]; then
        echo "Condition met. Returning..."
        return 0
    fi
    # Rest of the function code
}

Example: Automated Backup Script

Now that you’ve got the basics down, let’s create a more practical example. In this example, we’ll create a script that automatically backs up a directory.

!/bin/bash

# Set the backup directory
BACKUP_DIR="/home/user/backup"

# Create the backup directory if it doesn't exist
if [[ ! -d "${BACKUP_DIR}" ]]; then
   mkdir "${BACKUP_DIR}"
fi

# Archive the directory and save it to the backup directory
tar --create --gzip --verbose --file "${BACKUP_DIR}/mybackup.tar.gz" /home/user/mydirectory

# Print a success message
echo "Backup complete!"

This script sets the backup directory, creates it if it doesn’t exist, archives the directory, and saves it to the backup directory. It then prints a success message.

Wrapping Up

Bash scripting is a valuable skill that can help you automate tasks and manage system configurations. With the steps and example provided in this blog post, you should be able to write your first Bash script and start exploring the power of Bash scripting.

Leandro Padula

Software development expert with a proven track record of delivering successful solutions for companies of all sizes.

Share this article

Comments

  1. Curious, how long did it take you to learn bash? I started years ago and have never felt like I’ve never even come close to “learning” it.

    Reply
    • Hi Corylbs!

      I’ve been working with bash scripting for 12 years now. While you can learn the basics of bash scripting relatively quickly, becoming an expert requires lots of practice. The most challenging aspect is finding good tutorials or documentation that adhere to best practices. Unfortunately, the internet is filled with solutions that are either ineffective or fail to consider security implications. That’s precisely why I’ve started this post series – to share my expertise and help others navigate this challenge.

      Reply

Leave a Comment

Related articles

Ready to get your project started?

Book a call