Shell Script: editFile.sh


This shell script is ideal for editing system files. It saves the file before and after opening a “vi” session on the file. Each saved file is date/time stamped.
 

#! /bin/sh

cd
ROOT="`pwd`/"
SAVEDIR="${ROOT}save_`date +'%Y-%m-%d'`/"
mkdir -p ${SAVEDIR}

saveFile() {
    BEFAFT=$1
    shift
    DATETIME=$1
    shift
    FILE=$1
    shift
    SAVENAME="${SAVEDIR}save_${DATETIME}_${BEFAFT}_`echo ${FILE}|tr -c '[:alnum:]' '_'`"
    cp ${FILE} ${SAVENAME}
}

for FN in $*
do
    NOW="`date +'%Y-%m-%d_%H-%M-%S'`"
    saveFile BEFORE ${NOW} ${FN}
    vi ${FN}
    saveFile AFTER_ ${NOW} ${FN}
done