The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Use Bash to automate repeating tasks

posted on 15.1.2023 by Below Surface in "Bash"

Imagine you are running a self hosted blog on a Linux machine and want to update the live website after making changes locally. This is when a Bash script will come in handy. In a Bash script you can gather all single commands that you would normally run manually to update the website via the terminal.

After SSH'ing into your server, just create a file and open it in a text editor:

$ touch update.sh
$ nano update.sh

Let's imagine, you pushed your local changes to your GitHub repository and now want to pull the files onto the live server. In our case, we have the following specs:

What we want to do is:

To archive this, the update.sh file, may look like this:

#!/bin/bash
pm2 stop all
pm2 delete all
cd /var/www
rm -rf website.com
git clone git@github.com:username/website.com.git
cd website.com
cp ~/.env .
npm install
pm2 start server.js
cd client
npm install
npm run build
pm2 start npm -- start

Now, all you need to do is save the file, exit the editor and run

$ bash update.sh


By the way: Now you still need to SSH into your server to run the script. But you can instead use GitHub Actions to run it, every time a new commit is pushed to your repositories main branch (or any other).

Tags:

bash
shell
linux
automation