I have a script which when executed will produce some files. I modified the script by adding the following two lines at its top

mkdir ABC
cd ABC

So that the formed new files will be inside the directory ABC. My question is how can I add current date to this directory name ABC such as it becomes ABC_mar_26 (no specific criteria on date format, ABC_03_26 is also okay) if I run the script on march 26th.

  • 1
    I strongly recommend you use %Y-%m-%d or %F if it's available. That format will display chronologically in a directory listing. – glenn jackman Mar 26 '16 at 15:33

To get ABC_03_26:

mkdir "ABC_$(date +'%m_%d')"

If you want month name:

mkdir "ABC_$(LC_ALL=C date +'%b_%d')"

Note that %b give you locale's abbreviated month name, but with the first letter capitalized.

With zsh, you can:

mkdir "ABC_${(L):-$(LC_ALL=C date +'%b_%d')}"

or using prompt expansion:

$ LC_ALL=C; print -rl -- ${(L)${(%):-%D{%b_%d}}}
  • I often find it more readable to put the constant string in the date format: mkdir $(date +'ABC_%m_%d') – xenoid Aug 2 '19 at 12:02

Here is a concrete example application for your question, it might be also interesting for Windows/cygwin users. I have once created a .bat batch script to automatically backup files by creating a subfolder named with the current datetime. Firstly, variables are fetched from the %time% environment, and then formatted to evantually have a leading 0. The strings are then concatenated to a new variable %datetimef% and passed to mkdir:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%

set year=%date:~-4%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%

set datetimef=%year%%month%%day%-%hour%%min%%secs%

mkdir version%datetimef%
cp *.pdf version%datetimef%/
  • This is a Unix and Linux site. – xenoid Aug 2 '19 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.