Inserting Google Analytics Tracking Code using Shell Script

In most cases, you should be able to configure your CMS or blog template to insert the Google Analytics JavaScript tracking code at the end of every page in your web site.

However, you sometimes need to install the tracker code into static HTML pages which are not managed by the CMS, If you have a LOT of static HTML pages, then your fingers are in trouble.

Here’s the Bash shell script which inserts the Google Analytics tracker code into all static HTML pages. Please modify it before you run it, to meet your needs. Never forget to backup the original copy — it might work incorrectly for you:

#!/bin/bash
# inject-google-analytics
TRACKER_ID="UA-XXXXX-X"
TRACKER_CODE="<script type=\"text/javascript\">
var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");
document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));
</script>
<script type=\"text/javascript\">
try {
var pageTracker = _gat._getTracker('$TRACKER_ID');
pageTracker._trackPageview();
} catch(err) {}</script>"

find . -name '*.html.new' -delete
find . '(' -name '*.html' -and -not -name '*-frame.html' ')' | while read -r TARGET; do
  if grep -qiP "(<frameset|$TRACKER_ID)" "$TARGET"; then
    continue;
  fi

  if grep -qiF '</body>' "$TARGET"; then
    perl -pi -e "s/(<\/body>)/\n${TRACKER_CODE////\/}\n$1/i" < "$TARGET" > "$TARGET.new"
  else
    { cat "$TARGET"; echo; echo "$TRACKER_CODE"; echo; } > "$TARGET.new"
  fi
  if ! grep -qF "$TRACKER_ID" "$TARGET.new"; then
    echo "Failed to inject analytics script: $TARGET"
    cat "$TARGET.new"
    rm -f "$TARGET.new"
    exit 1
  fi
  mv -f "$TARGET.new" "$TARGET"
done

1 Comment Inserting Google Analytics Tracking Code using Shell Script

Comments are closed.