Skip to content
Home » Blog » Bash Script: Check 301s / Redirects

Bash Script: Check 301s / Redirects

Today I want to share with you a simple bash shell script to check a list of 301s.

Your Problem:

You have several 301s pointing to your site, or you changed old, still indexed URLs to some new URL structure and want to be sure they still point there.

What most people do:

You do it manually. The more URLs you need to check, the longer it takes. You might check once a week at most. Maybe you forget about it.

It’s your computers job to do that for you 🤖

How to run (bash) shell scripts?

Again, bash script is perfect for such things. If you are running Linux (which you should as an more technical SEO), all the tools needed for some quick and easy tools come shipped.

With MacOS you might have to install some like like curl and bash through a packet manager like homebrew. The default shell in MacOS is zshell.

The 301 / redirect check script

Here’s the script:

#!/bin/bash

if [ $# -eq 0 ]
then
    echo "usage: check.sh filename.txt https://target.com"
    exit
fi


for URL in `cat $1`
do
    if curl --silent -I $URL | grep "Location:" | grep -q "$2"
    then
	echo "$URL - OK"
    else
	echo -e "\033[1;31m$URL\033[0m"
    fi
done


Usage is simple.

./check.sh list_of_urls_to_check.txt "https://redirect-target.tld"


Again, don’t forget to make the script executable first (chmod +x check.sh).

The script will go through all the URLs in the .txt file you provided as first parameter and check if the HTTP Header field ‘Location’ points to the URL you specified as second parameter.

Improvements

You could run that script manually once a day. You could also run it as a cron, wrap around another script around that which sends you an email or triggers something else when an error was found. Of course you could also edit the script itself doing so.

Hope you find it useful.

Until the next one.

Leave a Reply

Your email address will not be published. Required fields are marked *