Occasionally I have a scenario where I want to run a few Terminal commands one after the other. For example, clear a few folders of files, run a build script and then copy the contents somewhere.

Do this enough times and it gets more than a little tiresome. Thankfully, tasks of this nature can be bundled up into a little script you can include in your project and run at any time from the Shell (Terminal).

We will run through a little example here. As much for the benefit of my future self as anything else.

In this case I’m making a little shell script which I can run by navigating to the folder it resides in and running buildSite.sh from the command line.

# Move into the right folder
cd ~/Sites/Demo/ 
# delete all files in the dist folder
rm -rf dist/**
# delete all files in the server folder
rm -rf /Destination/For/Build/Site/**
# Run a parcel build
parcel build index.html --public-url './' --no-source-maps --no-cache --no-minify
# Copy the build up to the proto folder
cp -R dist/ ~/Sites/Demo/ 
# Tell me it has finished
echo All done.

So what on earth is going on here. First, you need to save your Shell script with a .sh extension.

You also need the first line of the script to ‘tell’ the environment which Shell to use. I’m using ZSH but you could just as easily opt for Bash or something else. For example, if I was using Bash the first line would look like this: #!/bin/bash

After that you are just writing out the commands you want to happen, just as if you were typing them in a Terminal. I’ve added an extra line at the end echo All done. The echo command just prints the text that follows the command to the screen.
I’m using it to provide some definitive feedback in the Terminal when everything has finished.

When you have finished writing your script, before you can run it you need to set the correct permissions from the Terminal:

chmod +x ~/Sites/Demo/buildSite.sh

Then it’s just case of running the script from the Terminal. You can enter the path to the script from where you are e.g. ~/Sites/Demo/buildSite.sh, or, if you are already in the relevant folder just run with the script name e.g.