Bash script for beginners
June 25, 2012 in Bash script
Bash scripting for beginners Part 5
Date and Time
So far we have created a backup that works but there is a small problem everytime we run one of the previous scripts we created the backup in the same file. And what if we want to create separate backups that we can also have previous version of the backups? A good idea is to create file names that will contain the date and the time that this backup was created. In that way we will have a unique name every time we run the backup. To do so let’s create a new script and name it backup4.sh
gedit ~/Desktop/bash/code/backup4sh
write the following to the gedit :
#!/bin/bash # Bash with allaboutlinux.eu DATETIME="$(date +%d.%m.%Y_%H:%M:%S)" BKFILE=~/Desktop/bash/backup/backup$DATETIME.tar.gz BKFOLDER=~/Desktop/bash/code/ BKRESULT=~/Desktop/bash/backup/backup$DATETIME.txt tar -zcvf $BKFILE $BKFOLDER > $BKRESULT echo backup saved to $BKFILE and the results writtten to $BKRESULT$DATETIME
save and close. Now make the file executable
chmod +x backup4.sh
execute that file with
./backup4.sh
Just a quick explanation of the script:
This is just like the script from part 4 but I have added a new variable with the name DATETIME that is containing the current time and date when we execute the script. So every-time we execute the script that variable takes another value. A variable can also contain a previous defined variable just like in line 3 and line 5.
(date +%d.%m.%Y_%H:%M:%S) is used in order to get the current time and date. You can use only time or only date it’s up to you. For example if you just want the month and the year just use (date %m.%Y).
Note %m is for months but %M is for minutes. Most of the commands parameters are case sensitive.
in part 6 when i am trying to execute it ,it is showing…command not found at line no 5’Quit’
Hello Gulfam wani
Thank you very much for this comment!!!
This is an encoding problem with the quotation mark.
Check the quotation mark in line 6 (LIST=”Backup Quit”)and the different quotation mark in line 8(if [ $OPT = “Backup” ]; then).
The quotation mark in line 8 is correct
The quotation mark in line 6 is NOT correct
please manually change this and then everything will work!
Thank you again!
Best Regards
Allaboutlinux.eu
Thanks it is working now…..
very interesting tutorial