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

6,608

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
Share:
6,608

Related videos on Youtube

agmb
Author by

agmb

Updated on September 18, 2022

Comments

  • agmb
    agmb over 1 year

    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

  • Nitin Venkatesh
    Nitin Venkatesh over 11 years
    @agmb Yup, take a look at man date . Add %H:%M . Edited answer
  • agmb
    agmb over 11 years
    Thanks, but now I get an error everytime I run the bash tar: Cannot connect to File14August2012_16: resolve failed
  • Scott Severance
    Scott Severance over 11 years
    I find it quite useful to put the date at the beginning of the filename, in YYYY-MM-DD format. That way, directory listings are always sorted correctly. For example, 2012-08-15.filename.tar, generated by: tar -cvf "$(date +%F).filename.tar" /path/to/target.
  • Peter Smit
    Peter Smit over 11 years
    @agmb The colon is causing this. Use double-quotes around the path.