DEV Community

Celestine Ekoh-Ordan
Celestine Ekoh-Ordan

Posted on • Edited on • Originally published at blog.ekohordan.com

Getting Started with Bash Scripting for Web Developers

Web developers are constantly seeking ways to increase their efficiency, and one key way to do that is to automate, at least to an extent, most mundane and repetitive tasks that constitute our daily activities. One tool that can help with that and requires no overhead to begin to use and leverage upon is Bash Scripting.

This article aims to get you started with Bash. My aim is to highlight its potential to be an addition to your workflow as a developer.

As might be obvious from the preceding statements, I'll assume that you have a bit of familiarity with software development, you know what Git and Github are and at least know what a terminal is.

Having said that what you will need in order to follow along with this tutorial includes:

  • A terminal (Linux or Mac)
  • A text editor

If you have these, we can begin.

Introduction

What is Bash and Bash Scripting

Bash stands for Bourne Again Shell and it is a command processor or interpreter in which a user can type in executable commands. A Bash script, on the other hand, is, simply put, a collection of Bash commands.

terminal

A simple hello world script

Let us begin with a simple hello world script.
In Bash, the construct for printing out something to the terminal(console) is the echo keyword. It is the equivalent of console.log in JavaScript which simply prints out the arguments supplied to it.

In order to make our first script we need to create a simple file called hello_world.sh.

$ touch hello_world.sh

To begin with our hello world script we would create a Bash command in our script which we can run and execute. Open the hello_world.sh file in your text editor and enter the following

  #!/bin/bash

  echo "Hello world"

Making an executable

In order to run this script, we would need to make it an executable file. If you list out the files in the current directory using ls -al, the hello_world.sh file we created would be listed with the following properties similar to what is shown below

list-files

The -rw-r--r-- section shows that the current user only has read and write permissions on that file.

In order to execute this script run the following command to add execute permissions for the current user.

$ chmod 755 hello_world.sh

Run ls -al once more to see the current permissions and you should see something similar to this. The x showing that the current user has execute permissions for this file.

list-executable

Running the script

In order to execute our Hello world script just run ./hello_world.sh in the current directory. This Bash script simply prints out the string "Hello world" to the terminal when it is executed.

Exciting right? πŸš€πŸ”₯

What if we could make this function take in an argument and print out that argument instead. And if no argument is provided it can just print out a default "Hello world" greeting.

We will update the script to handle receiving and use of arguments.

Bash Scripting Basics

Command line parameters

We can pass arguments to our script by supplying them in front of the call to our script. So let's say we wanted to execute our script and pass an argument (e.g a name) to it, we can do it as follows

hello-param

Executing our script this way passes the string of characters "Jane" to our script. However, we currently have no way of using this parameter in our current script.

Command line arguments are usually supplied to the running script as a list of arguments represented by $1 for the first argument, $2 for the second and so on.

So in our case above, we can update our script to accept a name and print out a "Hello" greeting along with the name. Edit your hello_world.sh file and replace it with the following:

  #!/bin/bash

  echo "Hello" $1

Executing ./hello_world.sh Jane should print out the expected result

hello-jane

if...else conditionals

Now we have our script printing the greeting with a provided name. If you run the script without any arguments you will notice it just prints out "Hello". We can extend its functionality by making use of conditionals within Bash. A simple if...else statement would do.

Update your script to the following:

  #!/bin/bash

  if [ $1 ]; then
    echo "Hello" $1
  else
    echo "Hello World"
  fi

With the above, we are checking if a command line argument was supplied to the script and then we print the greeting with the argument, otherwise we print "Hello World". Run it a few times to verify this.

A more practical Bash script

Now I understand you can't do much with just a "Hello World" script, so we will try to build a script you can actually use.

For this, we will look to solve a problem that I think developers have in their daily activity, which is cloning a Github repository and changing directory into the newly cloned repository in one single step.

Create a new file in a folder of your choice called clone_repo.sh. Add execute permissions to the file by running chmod 755 clone_repo.sh

Enter the following into it

  #!/bin/bash

  echo "Initializing git clone $1"

  git clone $1

  basename=$(basename $1)
  folder_name=${basename%.*}

  echo "Changed directory to $folder_name"
  cd $folder_name
  exec bash

What the above script does is fairly obvious. Firstly we print out a message saying notifying the beginning of the git clone. Then we run the actual git clone command. (Note this script assumes you already have git installed in your environment).

Next, we make use of basename which is a standard Unix program to get the last name from the provided Github URL ignoring any trailing slashes. The next line only sanitizes it in order to get the correct pathname in cases where the Github URL also has a **.git extension at the end e.g https://github.com/ceoehis/reactive-weather.git.

After obtaining the correct folder name we notify the user with where we are with the set up via another echo statement and then issue a command to cd or change directory into the folder name.

The final line is a call to execute the current Bash instance at the end of our script in order for the cd command to take effect on the parent shell. This is because Bash scripts are usually run in a subshell and cannot change the working directory of the parent shell. This means that the effect of the cd command would ordinarily not affect the parent shell. In order to have the cd command take effect on the parent shell, we need to execute the child Bash instance in the script as above.

Finally, we need to execute this script and pass a Github repository as an argument.

$ ./clone_repo.sh https://github.com/ceoehis/reactive-weather.git

clone-repo

Voila! The repo was cloned successfully and the resulting directory became the current working directory, thanks to our script. πŸ”₯πŸ’ͺ🏽

Our demo script can be improved upon in a few ways. See if you can improve the user experience for this script by handling potential errors, and maybe even prompting a user with the correct usage information for cases when they don't supply a Github URL.

The possibilities with shell scripting are endless, from printing names to the console to automating several tasks. This tutorial is a primer to get you started with basic Bash constructs and scripts. You can find more resources in the links below.

Shell Scripting tutorial
Bash for beginners

Thanks for reading. This article was originally posted on my blog

Top comments (1)

Collapse
 
jrandall profile image
Joshua C. Randall

This is great, Celestine. I would also always recommend to those new to bash scripting to adopt a "safe shell script" incantation at the top of the script, to set some modes that tend to make it harder to make mistakes and make the script fail if any of the commands you run in it fail.

The usual incantation I use is "set -euf -o pipefail" which can be added right after the hash-bang line.

A good explanation of this can be found at sipb.mit.edu/doc/safe-shell/