Shell Script: saveFiles.sh


This shell script is useful for saving files before editing them. For example, one might use this script to save a critical system file before making changes. The Saved files are placed in a specific directory under the homedir of the account executing the shell script.

#! /bin/sh
#
# Save a file

MYname=`basename $0`
ROOT="${HOME}/${MYname}/"
LOGDIR="${ROOT}logs/`date +'%Y-%m'`/"
SAVEDIR="${ROOT}saved_files/`date +'%Y-%m'`/"
NOW=`date +'%Y-%m-%d_%H-%M-%S'`
LOGFILE=${LOGDIR}${MYname}.log_$$_${NOW}
SAVEFILEPRE=${SAVEDIR}_
SAVEFILESUF=_saved_${NOW}_$$
mkdir -p ${ROOT}
mkdir -p ${LOGDIR}
mkdir -p ${SAVEDIR}

log() {
    echo `date +'%Y-%m-%d_%H-%M-%S'`" $*" | tee -a ${LOGFILE}
}
cmd() {
    log "$*"
    $* 2>&1 | tee -a ${LOGFILE}
}
saveFile() {
    FILESRC=$1
    FILEDST=${SAVEFILEPRE}`echo ${FILESRC}|tr -c '[:alnum:]' '_'`${SAVEFILESUF}
    echo ${FILESRC} > ${FILEDST}_source_name
    cmd cp -p ${FILESRC} ${FILEDST}
}    
log Saving the files from the command line to ${SAVEDIR}

for FN in $*
do
    saveFile ${FN}
done

log Finish