Intro to Scripting and Automation in BASH/ZSH

Lucas Thinnes
3 min readSep 8, 2021

This week I began a dive into the world of shell scripting. It is often referred to as “Bash Scripting” as the source of the default terminal is generally BASH (more can be read upon this subject here) but the scripts can also be run while using ZSH (which is what I prefer). The whole idea behind writing shell script is to automate certain tasks which become repetitive over time, such as creating a certain combination of files / directories or running a certain set of commands from the command line in order to initialize or run an application. I wanted to give a brief introduction to the language and show how it is possible to combine a handful of terminal commands into one.

CONFIGURATION

The first thing you need to do is create a file with a .sh extension (short for shell), and put this at the top of the document:

#! /bin/bash

The first two characters are referred to as a “she-bang”. It is the absolute path to the location of BASH on your OSX machine. The location must be dealt from BASH as I found making this point to the location of ZSH causes errors in user input and conditionals. This line is necessary for executing any shell script. I will include a commented list of operations for you to duplicate and test out within the document:

# Hello Worldecho "Hello World!"# VariablesNAME="Your Name"
echo "My name is $NAME."
# Inputread -p "What is your age?: " AGE
echo "You are $AGE!"
# ConditionalsIf Else
if [ "$NAME"=="Your Name" ]
then
echo "What's good?"
else
echo "Nah bro."
fi
# Else Ifif [ "$NAME"=="Your Name" ]
then
echo "Yo not much"
elif [ "$NAME"=="Not Your Name" ]
then
echo "Big what's up."
fi
# ComparisonNUM1=13
NUM2=5
if [ "$NUM1" -gt "$NUM2" ]
then
echo "Idk about that."
fi

The file will be run in the terminal via the command ./file-name.sh.

The syntax should look fairly familiar with the exceptions of a few quirks such as the intricacies of If statements being lodged within array brackets and a greater than comparison taking the form of “-gt”.

Next, I would love to show a very simple demonstration of what an automation sequence may look like in which we create a directory, and a file with text enclosed all in one command!

A SIMPLE AUTOMATION

So check this out, if you have any of that previous code that I copied over in your text editor (minus the she-bang), remove it and replace it with the following commands in sequence:

#! /bin/bashmkdir new-folder
touch "new-folder/new.txt"
echo "What's good, world!" >> "new-folder/new.txt"
echo "Process complete!"

Just like that! Check out the directory and the contents of the file :)

Although this is a super simple and straightforward example of automating using shell script, I hope that it give you a hint at the potential evident when imagining this sort of process and how much time it can save!

Hope you enjoyed reading about this, and until next time…

--

--