DEV Community

loading...
Cover image for How to write your first Bash script?

How to write your first Bash script?

bobbyiliev profile image Bobby Iliev Originally published at devdojo.com ・4 min read

Introduction

Bash scripting lets you automate a lot of your tasks on Linux and UNIX systems. Bash combines the power of the Linux commands and tools with a powerful and robust scripting language.

Bash is widely available on various operating systems. In many cases, Bash is also the default command interpreter on most Linux systems.

In this article, I will show you how to write your first Bash script!

Prerequisites

Before you get started you would need a bash terminal and a text editor.

I will be using an Ubuntu Droplet deployed on DigitalOcean. If you wish to follow along you can sign up for DigitalOcean via my referral link below and you will get $100 free DigitalOcean credit:

Free $100 DigitalOcean Credit

Planning the script

As an example, we will write a script that would gather some useful information about our server like:

  • Current Disk usage
  • Current CPU usage
  • Current RAM usage
  • Check the exact Kernel version

Feel free to adjust the script by adding or removing functionality so that it matches your needs.

Writing the script

The first thing that you need to do is to create a new file with a .sh extension. I will create a file called status.sh as the script that we will create would give us the status of our server.

Once you've created the file, open it with your favorite text editor.

On the very first line of our Bash script we need to specify the so-called Shebang:

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

All that the shebang does is to instruct the operating system to run the script with the /bin/bash executable.

Adding comments

Let's start by adding some comments so that people could easily figure out what the script is used for. To do that right after the shebang you can just add the following:

#!/bin/bash

# Script that returns the current server status
Enter fullscreen mode Exit fullscreen mode

Adding your first variable

Then let's go ahead and add some variables which we might want to use throughout the script.

To assign a value to a variable in bash, you just have to use the = sign. For example, let's store the hostname of our server in a variable so that we could use it later:

server_name=$(hostname)
Enter fullscreen mode Exit fullscreen mode

By using $() we tell bash to actually interpret the command and then assign the value to our variable.

Now if we were to echo out the variable we would see the current hostname:

echo $server_name
Enter fullscreen mode Exit fullscreen mode

Adding your first function

In order to create a function in bash you need to use the following structure:

function function_name() {
    your_commands
}
Enter fullscreen mode Exit fullscreen mode

Let's create a function that returns the current memory usage on our server:

function memory_check() {
    echo ""
    echo "The current memory usage on ${server_name} is: "
    free -h
    echo ""
}
Enter fullscreen mode Exit fullscreen mode

Quick run down of the function:

  • function memory_check() { - this is how we define the function
  • echo "" - here we just print a new line
  • echo "The current memory usage on ${server_name} is: " - here we print all a small message and the $server_name variable
  • } - finally this is how we close the function

Then once the function has been defined, in order to call it, just use the name of the function:

# Define the function
function memory_check() {
    echo ""
    echo "The current memory usage on ${server_name} is: "
    free -h
    echo ""
}

# Call the function
memory_check
Enter fullscreen mode Exit fullscreen mode

Adding more functions challenge

Before checking out the solution, I would challenge you to use the function from above and write a few functions by yourself.

The functions should do the following:

  • Current Disk usage
  • Current CPU usage
  • Current RAM usage
  • Check the exact Kernel version

Feel free to use google if you are not sure what commands you need to use in order to get that information.

Once you are ready, feel free to scroll down and check how we've done it and compare the results!

Note that there are multiple correct ways of doing it!

Sample script

Here's what the end result would look like:

#!/bin/bash

##
# BASH script that checks:
#   - Memory usage
#   - CPU load
#   - Number of TCP connections 
#   - Kernel version
##

server_name=$(hostname)

function memory_check() {
    echo ""
    echo "Memory usage on ${server_name} is: "
    free -h
    echo ""
}

function cpu_check() {
    echo ""
    echo "CPU load on ${server_name} is: "
    echo ""
    uptime
    echo ""
}

function tcp_check() {
    echo ""
    echo "TCP connections on ${server_name}: "
    echo ""
    cat  /proc/net/tcp | wc -l
    echo ""
}

function kernel_check() {
    echo ""
    echo "Kernel version on ${server_name} is: "
    echo ""
    uname -r
    echo ""
}

function all_checks() {
    memory_check
    cpu_check
    tcp_check
    kernel_check
}

all_checks
Enter fullscreen mode Exit fullscreen mode

Debugging and testing

In order to debug your bash scripts, you can use -x when executing your scripts:

bash -x ./your_script.sh
Enter fullscreen mode Exit fullscreen mode

Or you can add set -x before the specific line that you want to debug, set -x enables a mode of the shell where all executed commands are printed to the terminal.

Another way to test your scripts is to use this fantastic tool here:

https://www.shellcheck.net/

Just copy and paste your code into the textbox, and the tool will give you some suggestions on how you can improve your script.

Learn More

Bash scripting is awesome! No matter if you are a DevOps/SysOps engineer, developer, or just a Linux enthusiast, you can use Bash scripts to combine different Linux commands and automate boring and repetitive daily tasks, so that you can focus on more productive and fun things!

To learn more about Bash you can take a look at the following Bash eBook here:

Introduction to Bash scripting eBook

Feel free to share your script with me by tagging me on Twitter: @bobbyiliev_

Discussion

pic
Editor guide
Collapse
booyaa profile image
Mark Sta Ana

Helpful tip for new bash script writers is to use shellcheck to catch common errors and unsafe usage. Most editors provide support for shellcheck. shellcheck.net/

Collapse
bobbyiliev profile image
Bobby Iliev Author

Very good point! Thank you for bringing it up! It was actually already mentioned in the eBook here but I've added it to the post as well! 🙌