1

How can I create directories named as days of the week (i.e Monday, Tuesday, .... Saturday) inside a directory like /tmp/ in one command only?

Like combination of mkdir with date +%A or any other.

mkdir -p /tmp/"$(date +%A)"  --->  /tmp/Tuesday

Should be as below after command executes.

/tmp/Monday
/tmp/Tuesday
.
.
.
/tmp/Saturday

I want this in a single command, not a script.

  • 3
    mkdir Mon Tue Wed Thu Fri Sat Sun ? – ilkkachu Mar 28 '17 at 11:16
3

You can use the following 'command' to get the desired result:

for i in {1..7}; do mkdir /tmp/$(date +"%A" --date "$i days ago"); done
  • (assuming GNU date (and that POSIXLY_CORRECT is not in the environment) and zsh or recent versions of ksh93/bash/yash -o brace-expand and that $IFS was not modified and that you're not in a locale (like kw_GB.UTF-8) where day names contain blanks or wildcard characters). – Stéphane Chazelas Mar 28 '17 at 12:30
  • 1
    If run today Tuesday 2017-03-28 at 00:30 in the morning in most of Europe, if would be missing Sunday as 1 days ago would be Monday 2017-03-27 00:30 and 2 days ago would be Saturday 2017-03-25 23:30 because of the clock change on Sunday morning. Monday would be listed twice as 7 days ago would be Monday 2017-03-20 23:30. – Stéphane Chazelas Mar 28 '17 at 12:55
3

You can use brace expansion:

mkdir -p /tmp/{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}

The above is equivalent to this (which is also a single command):

mkdir -p /tmp/Sunday /tmp/Monday /tmp/Tuesday /tmp/Wednesday /tmp/Thursday /tmp/Friday /tmp/Saturday
  • Using Brace expansion is simple & useful trick. Glad to know this :) – Rahul_Dange Apr 4 '17 at 11:35
3

With zsh:

zmodload zsh/langinfo # if not already loaded
mkdir /tmp/${(v)^langinfo[(I)DAY_*]}

That uses day names in your locale. As a single command:

zsh -c 'zmodload zsh/langinfo && mkdir /tmp/${(v)^langinfo[(I)DAY_*]}'

$langinfo is a special associative array that exposes some locale settings including day names. $langinfo[(I)DAY_*] would output the keys of that array that match DAY_* (that is DAY_1, DAY_2...). With the (v) parameter expansion flag, we expand the values for those keys instead. ^ distributes those elements so that it becomes /tmp/value1, /tmp/value2...

With any POSIX-like shell, you can also do:

(cd /tmp && IFS=';' && set -o noglob && mkdir $(locale day))

locale day returns a ;-separated list of day names in the current locale. We use the split+glob operator on it (leave the $(...) command substitution unquoted) after having disabled the glob part (set -o noglob) and tuned the split part to split on ; (IFS=';').

  • Thanks for nice detailed explanation. Helps at lot for gaining something new. – Rahul_Dange Apr 4 '17 at 12:17

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.