Writing Your First Bash Script

By Anurag Singh

Updated on Dec 18, 2024

Writing Your First Bash Script

In this tutorial, we're writing your first bash script.

Bash scripting is an essential skill for anyone working with Linux or Unix systems. It allows you to automate tasks, manage system operations, and simplify repetitive tasks. In this tutorial, we’ll walk through creating, running, and debugging a simple Bash script, with detailed explanations of key concepts, including the purpose of the #!/bin/bash shebang.

Prerequisites

Before getting started, ensure you have the following:

  • A KVM VPS or dedicated server with any Linux distro installed.
  • A non-root user with sudo privileges.
  • Basic knowledge of Linux commands.

What is a Bash Script?

A Bash script is a plain text file containing a series of commands that are executed sequentially by the Bash shell. It’s a way to combine multiple commands into a single file, making them easier to manage and reuse.

Creating Your First Bash Script

1. Setting Up the Environment

Ensure you have Bash installed on your system. Most Linux distributions and macOS include Bash by default. You can check the version by running:

bash --version

2. Understanding the Shebang

The first line of a Bash script is the shebang, which tells the system what interpreter to use to execute the script. For Bash scripts, the shebang is:

#!/bin/bash

This line ensures that the script is executed with the Bash shell, regardless of the default shell on your system.

3. Creating the Script File

Open a terminal.

Use a text editor to create a new file. For example:

nano my_first_script.sh

Add the following content to the file:

#!/bin/bash

# This is my first Bash script
echo "Hello, World!"

Save and exit the editor. In nano, press Ctrl+O, hit Enter, and then press Ctrl+X.

Running Your Bash Script

1. Making the Script Executable

Before running the script, you need to make it executable. Use the chmod command:

chmod +x my_first_script.sh

2. Executing the Script

Run the script using:

./my_first_script.sh

You should see the output:

Hello, World!

Debugging Your Bash Script

Debugging is an essential skill when writing scripts. Bash provides several tools to help you find and fix errors.

1. Using bash -x

Run your script with the -x option to see each command executed:

bash -x my_first_script.sh

This will show a trace of each command and its arguments as they are executed.

2. Adding set -x and set +x

You can enable and disable debugging within the script by adding set -x (enable) and set +x (disable):

#!/bin/bash

set -x  # Start debugging
echo "Debugging enabled"

set +x  # Stop debugging
echo "Debugging disabled"

3. Checking for Syntax Errors

Use bash -n to check your script for syntax errors without executing it:

bash -n my_first_script.sh

4. Using trap for Debugging

The trap command allows you to run custom commands when the script exits or encounters specific signals. For example, to debug errors:

#!/bin/bash
trap 'echo "Error on line $LINENO"' ERR

# Simulate an error
echo "This will work"
false  # This command will fail

When the script encounters the false command, it will output:

Error on line 6

Best Practices for Writing Bash Scripts

Use Comments: Always include comments to explain the purpose of your script and its key sections.

# This script greets the user
echo "Hello, $USER!"

Test Your Script: Test your script in a safe environment before deploying it on a production system.

Handle Errors Gracefully: Use conditional statements to check for errors and handle them appropriately.

if [ -f /path/to/file ]; then
    echo "File exists."
else
    echo "File does not exist."
fi

Use Meaningful Variable Names: Choose descriptive variable names to make your script easier to understand.

Follow Permissions Guidelines: Only grant execute permissions to scripts that are safe to run.

Next Steps

With your first Bash script complete, you’re ready to explore more advanced topics, such as working with variables, loops, and functions. Bash scripting is a powerful tool that will enhance your efficiency and capability in system administration and beyond. Happy scripting!