A directory with automatic time in it in a unix shell

I want to create a script where the newly created directory will automatically have the current time as part of the name.

syntax

mkdir mydir[min-hour-day-month-year] 

so the last directory will be called

 mydir101718052012 

created in an hour

 mydir111718052012 

etc.

Sorry for the simple question, I'm new to unix and I use bash

Editing: Why shouldn't it be right? How can i do this?

 newdir = mydir$( date +%Y-%m-%d-%H-%M-%S) cp new.txt newdir/new1.txt 
+4
source share
2 answers

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.

+3
source

If your date implementation supports these options, you can simply:

 mkdir mydir$( date +%M%H%d%m%Y ) 

Please note that this does not insert hyphens in the name according to your pattern. To get hyphens, as in your original description:

 mkdir mydir$( date +%M-%H-%d-%m-%Y ) 
+5
source

Source: https://habr.com/ru/post/1413174/


All Articles