Creating files with dates

I mentioned in my previous entry that we are using some pretty tedious directory names, like 2013-09-26-Restaurant-Menu. We are frequently copying a template folder that has a similar name. Even with a wildcard to reference the template folder, copying it to a new folder with the specified format and then changing into that directory is a pain. I wrote my very first shell script to get around this issue. Here’s how you can do the same.

In your terminal, check to see if ~/bin exists. If not, create it, cd into it and then create a file called dcp
Add the following text to dcp:

1
2
3
4
5
6
7
8
#!/bin/bash
# This will copy a directory, adding the date to the beginning
# of the file name and cd into the new directory
# Date format: 2013-10-01-
 
nowDate=$(date +%Y-%m-%d-)
fileName=$nowDate$2
cp -rv $1 $fileName && cd $fileName
#!/bin/bash
# This will copy a directory, adding the date to the beginning
# of the file name and cd into the new directory
# Date format: 2013-10-01-

nowDate=$(date +%Y-%m-%d-)
fileName=$nowDate$2
cp -rv $1 $fileName && cd $fileName

Now you need to create an alias. Edit your ~/.bash_profile to add the following line:

1
alias dcp='. ~/bin/dcp'
alias dcp='. ~/bin/dcp'

You can change the alias to whatever you want, but I chose dcp for Date Copy.
Now restart your terminal and you can use the dcp command as follows (using a directory called “test” as an example):

1
dcp test testnew
dcp test testnew

Which should display the following result

1
‘test’ ->2013-10-01-testnew’
‘test’ -> ‘2013-10-01-testnew’

In addition to creating the directory, the new directory will now be your current working directory. 
Our current template is 2013-09-27-QUnit-Template, so here is how you would create a new project using wildcards:

1
dcp *QUnit* New-Project
dcp *QUnit* New-Project

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *