add md5sum to shell scripts

Written by cobalt on August 6th, 2012

Sometime it is desired to add a hash to scripts to avoid scripts altered by someone, this can be done in the following way:

#!/bin/bash
#MD5SUM=6b780d787ef345256c3a1faa35d3f1d5
 
function add_md5sum() {
  tmpf=$(mktemp /tmp/$(basename $0).XXXXXX)
  grep -v "^#MD5SUM=" $1 >$tmpf
  md5sum=$(md5sum $tmpf | cut -d ' ' -f1)
  sed -e "s|^\(#!/bin/bash.*\)$|\1\n#MD5SUM=$md5sum|" < $tmpf > $1
  rm -f $tmpf
}
 
function chk_md5sum() {
  osum=$(grep -v "^#MD5SUM=" $1 | md5sum | cut -d ' ' -f1)
  isum=$(grep "^#MD5SUM=" $1 | head -1 | cut -d= -f2)
  if [ "$isum" = "$osum" ]; then
    echo "sum ok: $isum"
    exit 0
  else
    echo "sums differ o:$osum i:$isum"
    exit 1
  fi
}
 
function usage() {
  echo "$0 add|chk file"
}
 
if [ -z "$2" ]; then
  usage
else
  case $1 in
    add) add_md5sum $2 ;;
    chk) chk_md5sum $2 ;;
    *)   usage ;;
  esac
fi
 

Comments are closed.