#!/bin/sh # Copy the N versions of a file for log or backup rotation # Stephane Bortzmeyer USAGE="Usage: $0 [-n number-of-copies] [-v] [-c] filename ..." TEMP=$(getopt -o "n:vch" -- "$@") if [ $? != 0 ]; then echo $USAGE >&2 exit 1 fi set -e # Yes, some people prefer: # ncopies=${COPY_N_FILES:-"5"} if [ -z "$COPY_N_FILES" ]; then ncopies=5 else ncopies=$COPY_N_FILES fi if [ -z "$MODE_NEW_FILE" ]; then mode=0600 else mode=$MODE_NEW_FILE fi verbose=0 create=0 eval set -- "$TEMP" while true ; do case "$1" in -n) ncopies=$2; shift 2;; -v) verbose=1; shift;; -c) create=1; shift;; -h) echo $USAGE >&2; exit 0;; --) shift ; break ;; *) echo "Internal error!" >&2 ; exit 1 ;; esac done if ! which seq > /dev/null; then echo "Cannot find command \"seq\" in PATH" >&2 exit 1 fi if [ -z "$@" ]; then echo $USAGE >&2 exit 1 fi for filename in "$@"; do # Yes, we could drop seq and use shell arithmetic but I like the # power of seq for i in $(seq $((ncopies-2)) -1 0); do previous=$((i+1)) if [ -e "$filename.$i" ]; then if [ $verbose = 1 ]; then echo "Moving $filename.$i to $filename.$previous..." fi mv -f "$filename.$i" "$filename.$previous" fi done if [ -e "$filename" ]; then if [ $verbose = 1 ]; then echo "Copying $filename to $filename.$i..." fi cp -pf "$filename" "$filename.$i" elif [ $create = 1 ]; then if [ $verbose = 1 ]; then echo "Creating $filename with mode $mode..." fi touch "$filename" chmod $mode "$filename" else echo "Warning: $filename does not exist" >&2 fi done