I want to create script where newly generated directory automatically have the current time as part of name.
syntax
mkdir mydir[min-hour-day-month-year]
thus the recent directory will be named as
mydir101718052012
directory created after one hour
mydir111718052012
and so on.
Sorry for simple question, I am new to unix and I using bash
Edits: Why is not following correct ? How can I do it ?
newdir = mydir$( date +%Y-%m-%d-%H-%M-%S)
cp new.txt newdir/new1.txt
If your implementation of date supports these options you can simply do:
mkdir mydir$( date +%M%H%d%m%Y )
Note that this does not insert hyphens in the name as per your sample output. To get the hyphens as in your initial description:
mkdir mydir$( date +%M-%H-%d-%m-%Y )
I have the following functions set up in my bash startup scripts:
# Date Time Stamp
dts() { date +%Y-%m-%d-%H-%M-%S; }
# Date mkdir
dmkdir() { mkdir $(dts); }
I use them chiefly on the command line, if you want to run them inside a script, you'll have to either source the startup script or define the shell functions within the script. If you wanted to prepend a name (e.g. mydir
), you could easily give it an argument like this:
# Date mkdir
dmkdir() { mkdir "$@$(dts)"; }
This would be called like this:
$ dmkdir mydir
$ ls -d mydir*
mydir2012-05-18-11-38-40
This does mean that if your argument list contains spaces, they will show up in the directory name, which might or might not be a good thing.
You can assign a shell variable inside the shell function, this can be accessed outside the function:
dmkdir() { newdir="$@$(dts)"; mkdir $newdir; }
Used like this:
$ dmkdir mydir
$ cd $newdir
$ pwd
/tmp/mydir2012-05-18-12-54-32
This is very handy, but there are a couple of things that you have to be careful of: 1) you're polluting your namespace -- you may overwrite a shell variable called $newdir
created by a different process 2) It's very easy to forget which variable dmkdir is going to write to, especially if you have a lot of shell functions writing out variables. A good naming convention will help a lot with both issues.
Another option is to have the shell function echo the directory name:
dmkdir() { local newdir="$@$(dts)"; mkdir $newdir && echo $newdir; }
This can be called as follows:
newdir="$(dmkdir mydir)"
local
means that $newdir
isn't available outside of dmkdir, which is a Good Thing(TM).
The use of &&
means that you only echo the name of the directory if the directory creation is successful.
The $()
syntax allows you to load anything echoed to STDOUT to be loaded into a variable, and the single quotes ensure that if there are any spaces in the directory name, it still gets loaded into a single variable.
This gets around the namespace pollution problems inherent in the previous solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With