Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Make a file backup adding date and seconds to the filename and remove the original (See related posts)

// In the case where a report file exists and further data will be appened the user might forget to remove or rename it so this script segment queries the user and copies the file then deletes the original version. In this script the date appended includes seconds so that multiple runs during a day will create additional unique files

#!/bin/bash

#note no spaces around equals (=) sign
base_dir='/a_directory_path_name_with_trailing_slash/'
filename='report.txt'
answer='n'
#note lack of concatenation point
report=$base_dir$filename

if (test -f $report) then
    echo "############## ATTENTION ###################"
    echo "The report file exists and it will be overwritten!"
	echo "Would you like me to make a copy of it and delete the existing version?"
		read answer
		if [ "$answer" == y ]
		then
			#date with seconds in case more than one in a day
			date=`date +%Y%m%d_%s`
			#concatenate with a point in between
			backup="$filename.$date"
			
			cp $report $base_dir$backup
			echo "Created...$backup"
			rm -rf "$report" 
			echo "Original removed"
		fi
    #continue
else
    echo "Data will be appended to the existing report file!"
    exit
fi
#script ends


You need to create an account or log in to post comments to this site.