How to Make a Backup Script for Shell in Linux
For those who hack a lot of Linux at the command line interface, backing up files such as config files before editing is a good habit to have. IMHO anyway. So to save time, a little script can be written, chmod +x, and placed into /usr/local/bin or some other that users have in their executable shell PATH. I name mine “bu” to make it easy, and it takes one command line argument which is the filename of the file you want to make a backup copy of. It is called by running something like $ bu myfile
Here’s the code. Comments welcome ;) The code creates a timecode based on today’s date and the current time to the second, and appends that to the original filename. The a copy is saved with this new “timestamped” backup filename, right in the same directory. Easy-peasy!Â
#!/bin/bash OLDFILENAME=$1 DATECODE=$(date +%Y%m%d) TIMECODE=$(date +%H%M%S) NEWFILENAME="${OLDFILENAME}_backup${DATECODE}-$TIMECODE" cp $OLDFILENAME $NEWFILENAME SUCCESS=$? if [ $SUCCESS -eq 0 ];then echo "OK! Copied \"$OLDFILENAME\" to \"$NEWFILENAME\"" else echo "FAIL! You'll need to try again!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" fi
Posted under Linux
This post was written by Content Curator on April 13, 2010