Ubuntu: How to make a bash script generate a new filename every time it's run?



Question:

I'd like to make a .tar file of a particular directory every day of the week. The way I'd like to do it is with a bash script making a tar file every day with crontab.

I was wondering, is there a way to regulate the name of the tar file the the bash script makes? Right now it's the same every time the file is made, becase the bash has just one command:tar -cvf file.tar /home/name/folder/

But I'd like for it to be slightly differnt based on the day e.g. FileTus.tar , FileWed.tar, FileFri.tar,etc..

Is there a way to do this though terminal commands?

Thanks


Solution:1

The date command can produce a date as text in whatever format you want. You would then use it in a script something like:

tar -cvf File$(date +%a).tar /home/name/folder  

This would produce FileMon.tar, FileTue.tar as above. See man date for a description of the different date formats it can produce.


Solution:2

Instead of just names of days, why not do a full date format? That way the same filename ain't generated every week :)

Something like this -

nits@excalibur:~$ tar -cvf /home/nits/Desktop/File$(date +%d%B%Y).tar Music/  

would produce output like this -

nits@excalibur:~$ ls ~/Desktop/  File14August2012.tar  

For something along with a timestamp (as asked in the comments):

nits@excalibur:~$ tar -cvf "/home/nits/Desktop/File$(date +%d%B%Y_%H:%M).tar" Music/  nits@excalibur:~$ ls ~/Desktop/  File14August2012_20:14.tar  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »