Checking if a file has changed using Bash scripting

Linux Bash scripting is a powerful way to easily automate or simplify tasks. However the solutions are not always intuitive unless you are very familiar with the syntax (which I am not). For one particular script I wanted to launch a file in a text editor and then take an action afterwards only if the user had changed the file.

This solution seems to be working brilliantly:

MD5OLD=`md5sum ~/thefile | cut -d " " -f1`
vim ~/thefile
MD5NEW=`md5sum ~/thefile | cut -d " " -f1`
if [ "$MD5OLD" != "$MD5NEW" ]; then
    echo "The file has changed - do something here"
else
    echo "The file has not changed - don't do anything"
fi

The trick is to get an MD5 hash before launching the text editor, and then get another MD5 afterwards. Comparing the two MD5 hash values will tell you if the file has changed or not.

Leave a comment

Your comment