I have the following functions installed in my bash startup scripts:
# Date Time Stamp dts() { date +%Y-%m-%d-%H-%M-%S; } # Date mkdir dmkdir() { mkdir $(dts); }
I use them mainly on the command line, if you want to run them inside a script, you will have to either run the script or define shell functions in the script. If you want to add a name (e.g. mydir
), you can easily give it an argument like this:
# Date mkdir dmkdir() { mkdir " $@ $(dts)"; }
It will look like this:
$ dmkdir mydir $ ls -d mydir* mydir2012-05-18-11-38-40
This means that if your argument list contains spaces, they will appear in the directory name, which may or may not be very good.
You can assign a shell variable inside the shell function, it can be accessed outside the function:
dmkdir() { newdir=" $@ $(dts)"; mkdir $newdir; }
Used as follows:
$ dmkdir mydir $ cd $newdir $ pwd /tmp/mydir2012-05-18-12-54-32
This is very convenient, but there are a few things that you need to be careful about: 1) you pollute your namespace - you can overwrite a shell variable called $newdir
created by another process 2) It is very easy to forget which dmkdir variable will write, especially if you have many shell functions writing out variables. A good naming convention will help solve both problems.
Another option is to force the shell function echo the directory name:
dmkdir() { local newdir=" $@ $(dts)"; mkdir $newdir && echo $newdir; }
It can be called as follows:
newdir="$(dmkdir mydir)"
local
means $newdir
not available outside of dmkdir, which is a good thing (TM).
Using &&
means that you only echo the directory name if directory creation is successful.
The $()
syntax allows you to load everything that the echo into STDOUT to load into a variable, and single quotes ensure that if there are spaces in the directory name, it is still loaded into a single variable.
This concerns the namespace pollution inherent in the previous solution.