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 -

[email protected]:~$ tar -cvf /home/nits/Desktop/File$(date +%d%B%Y).tar Music/

would produce output like this -

[email protected]:~$ ls ~/Desktop/
File14August2012.tar

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

[email protected]:~$ tar -cvf "/home/nits/Desktop/File$(date +%d%B%Y_%H:%M).tar" Music/
[email protected]:~$ 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 about 1 month

    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

  • con-f-use
    con-f-use about 10 years
    Exactly how I would have done it. Nice answer. Btw: The usual way to include a date in an archive is filename$(date +%y%m%d). That assures that you can sort them by date in a standard file browser such as nautilus. Optionally you can include the time $(date +%y%m%d-%H%M%S) (or even nanoseconds S->N) depending on how unique it should be one can also include the process id to prevent collisions.
  • agmb
    agmb about 10 years
    thanks very much for that. Btw is there a way to add time to that too?
  • Nitin Venkatesh
    Nitin Venkatesh about 10 years
    @agmb Yup, take a look at man date . Add %H:%M . Edited answer
  • agmb
    agmb about 10 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 about 10 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 about 10 years
    @agmb The colon is causing this. Use double-quotes around the path.