Kornshell function to keep revisions of a file

Sometimes while developing scripts you want to keep backups of certain files, but are worried that over time the old versions will fill the filesystem and need housekeeping.

The following function will allow you to keep only <n> versions of a file (the default is 5 backups) with older ones getting removed automatically. 

# Usage: FN_keep_revisions <filename> [<revisions>:5]

function FN_keep_revisions
{
   typeset FSP=${1}
  typeset -i GEN=${2:-5}
  typeset -i NEXT

  while [ "${GEN}" -gt 0 ] ; do
    NEXT=$((GEN-1))
    if [ "${GEN}" -eq 1 ] ; then
      mv -f ${FSP} ${FSP}.${GEN}
    else
      mv -f ${FSP}.${NEXT} ${FSP}.${GEN}
    fi
    GEN=${NEXT}
  done
 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: