Create and Use Bash Scripts: A complete guide

Make the most of this powerful tool

Image for post
Image for post
Photo by Obi Onyeador on Unsplash

Bash scripts? What are they and how can we use them?

This tutorial is about just that, and is here to help you get the most out of this great feature. Bash is available out of the box on Mac and UNIX systems, so if you’re using either of the two you’re ready to go!

You’re welcome…

Prerequisites:

  • Some knowledge of the Mac terminal (guide HERE)
  • This tutorial is going to use VIM (guide HERE), but you could use any text editor

Terminology

Bash: “Bourne again shell”. There are many shells that can run UNIX commands, and the one used on the Mac Terminal is Bash

Command line: An interface for interacting with the operating system

Shebang: A String at the beginning of a script to indicate execution

Shell: A user interface for accessing an operating system’s services

Terminal: A command line interface to control the UNIX-based operating system that underlies the Mac

VIM: This is a contraction of Vi and IMproved. That is, it is a clone (with additions) of the vi text editor for Unix. In other words, it is a command-line interface for creating and manipulating files

A little help…

This tutorial is not an exhaustive guide to the bash terminal, and is rather a starter guide to scripting with some basic bash syntax. This guide does use VIM but you are certainly welcome to use other text editors.

Where each of the following commands are prefixed by, $, which indicates that this should be typed into the terminal. To make this clear I’ve written it as a quote followed by the $ symbol so you will see the following (followed by a command to type) within this guide:

$

Creating your bash script

Creating the bash script

We are going to create our first bash script (called, wonderfully myfirstscript). There’s an animated gif to help with this if you choose to scroll to the end of this section.

$ vim myfirstscript

Add the shebang line

From within VIM we need to tell the command line to run the code using bash. VIM requires that you edit the current line, i to insert will do just that, then type away!

#!/usr/bin/env bash

Add the echo line

From VIM we add an echo line, which will (in the end) write “Hello,World” to the console.

echo "Hello,World!"

Save the script

From within VIM we can (if we were editing a quick nudge of the escape key will allow us to do this) use the save command :wq

$ :wq

This will return us to the console. Awesome.

Make the script executable

From terminal run the following to make the script executable

$ chmod +x myfirstscript

Running the script

After all of that, this isn’t too difficult

$ myfirstscript

The video so you can see what to do? That’s right here:

Image for post
Image for post

Make the script Globally available

Running the script from this particular folder is great, but we really want to create utilities that can be run from anywhere on your device.

This section of the guide will help you with just that.

  1. Copy the script to /usr/local/bin by running the following command (sudo meaning you are running this as the super user):

$ sudo cp ./ffmpegscript /usr/local/bin

you may well be asked for you password. This is no problem — don’t panic as this is a side-effect of using sudo.

2. Set the environment variable

  • open the bash_profile

$ vim .bash_profile

  • Add the path export PATH=~bin:$PATH

Here is my .bash_profile:

Image for post
Image for post

3. save the result using :wq

:wq

4. Profit

You can now run the file from anywhere. In the case of this script

The basics

Strings

As we have seen a little earlier in this guide, we can use echo to print to the terminal. There aren’t any painful quotes here — we can just write (including any spaces) straight to the screen!

echo hello big scary world

The syntax for echo is as follows:

echo [option(s)] [string(s)]

But how can we see what the options are? We have a choice — the manual through man or the short documentation through help echo . Which would I recommend? At this point the shorter guide is probably enough

$ help echo

Using these parameters does bring back the quotations, simply because we need to use the escape characters

$ echo -e "\a Hello, World"

in the documentation \a gives an alert. For me, this gives a nice sound from the Mac and a bell symbol at the top of the Terminal screen (if I use iTerm).

Speaking of which, it looks like the following:

Image for post
Image for post

Multiple options? See the following:

$ echo -e “\a\n Hello, World”

Which puts our message on a new line. Escaping quotation marks will work…

Shell execution

You can use the output of a shell execution in a script. This basically uses the output of a shell as a variable (more on that in a minute):

$ echo "Hello, $(whoami)"

Arrays

Arrays can be used to store data link in any language. This doesn’t even need to be done in a script, as it can be run directly on the command like:

$ languages=(‘Swift’ ‘Python’ ‘Java’ ‘JavaScript’)

echo ${languages[3]}

This will predictably print Javascript (due to zero-indexed arrays)

Variables

Variables are declared with just the variable name, but are called with $.

I’ve set up a new script called myvariablesscript, and made it executable with chmod +x myvariablesscript.

within the script I’ve added the following code

Which means we need to provide a name, which it will say hello to whichever variable is passed.

Running with ./myvariablesscript:

Input: “Me”

expected output: Hello to Me

This is fine. But if you don’t provide a name? It will just output Hello to. This isn’t great.

So we can provide a default message if no name given:

Now if you don’t provide a name the following error is given:

./myvariablesscript: line 3: 1: Error: no name given

Can we do even better? Yes, yes we can.

We can provide a default variable:

so if no parameter is provided we see Hello to ME

User input

If you want something a little more interactive, you might want to use user input. This is done using the read keyword. The following is an alternative script to the one above that writes out a wonderful greeting message that is personalised for you.

Comparison and if statements

Again using examples of greetings, we can demonstrate the implementation of an if statement. Now this is tricky, as bash treats strings and number differently; however for this simple example equality == will do.

which, if your name is given as You will return Hello, you! and if not returns Good Morning followed by your name.

Here are the Comparisons for Number and Strings

Image for post
Image for post

The operator for numbers works the same way as that for strings, that is should be between two operands that is [20 -eq 20] resolves to true whereas [21 -eq 20] resolves to false.

Loops

Here we can list the files in the current directory.

Functions

To demonstrate the use of functions with parameters I’ll write a simple function to (in practice) replace the echo function

If we wanted more parameters we would refer to them sequentially, that is $2, $3 and so on.

Debugging

Ok, this is only debugging of a sort.

At the top of each file instead of using

#!/usr/bin/env bash

we can use

#!/usr/bin/env bash -x

to get some rather juicy information!

Conclusion:

This is the start, not the end of bash scripting. This should give you some of the (albeit basic) tools to be able to create works of beauty on your machine — all from the command line.

I hope this helps!

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store