Add Google Analytics Tracking Code to All Pages Automatically

Sam - May 30 '23 - - Dev Community

If you have many HTML pages in a directory, adding Google Analytics tracking code to all of them can be a bit frustrating.

In this short tutorial, I show you how to do it with a bash script that automatically does the job.

First, copy the code from your Google Analytics console, and paste it to a file named google-analytics.

Then, write the following code to a file, say add-gtag.sh and give it the execution permission:

chmod u+x ./add-gtag.sh
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash

# From: dotenx.com

# description: 
# Add Google Analytics to all HTML files in a directory. Google Analytics code should be in a file called google-analytics in the same directory as this script.

# usage:
# ./add-gtag.sh directory

# Tested on Mac-zsh


directory="$1"

if [ -d "$directory" ]; then
  for file in "$directory"/*.html; do
    if [[ -f "$file" ]]; then
      sed -i.bak '/<head>/r google-analytics' $file
    fi
  done
else
  echo "Directory not found."
fi

rm $directory/*.bak
Enter fullscreen mode Exit fullscreen mode

Now, all you need to do is to execute the script like this:

./add-gtag.sh <your directory>
Enter fullscreen mode Exit fullscreen mode

You can find this code here on GitHub too.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .