How to write your first Bash script?
Tags: linux, bash, devops, codenewbie
Published: 2021-01-04 17:35:17

# 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](https://m.do.co/c/2a9bba940f39)

# 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](https://en.wikipedia.org/wiki/Shebang_(Unix)):

```
#!/bin/bash
```

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
```

## 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)
```

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
```

## Adding your first function

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

```
function function_name() {
    your_commands
}
```

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 ""
}
```

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
```

## 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
```

# Debugging and testing

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

```
bash -x ./your_script.sh
```

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](https://github.com/bobbyiliev/introduction-to-bash-scripting)**

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