2

I want to create a lot of directories (manually, using the GUI).

I will then want to have inside them a markdown document with the same name as the directory, so this sort of tree:

624466
└ 624466.md
626665
└ 626665.md

How can I automate the .md file creation?

Tim
  • 33,500

3 Answers3

2

I would use inotify API provided by the kernel to monitor filesystem events. There is no need for an indefinite while loop, you can use a tool that uses the interface provided by the kernel to check for any changes on any file.

One of the tools that uses inotify is inotifywait. From man inotifywait :

inotifywait efficiently waits for changes to files using Linux's inotify interface.

It is not installed by default, it is a part of inotify-tools package. You can install it by :

sudo apt-get install inotify-tools

The script i am taking about can take the form :

#!/bin/bash
while IFS= read -r line; do
    parent="${line%% *}"
    child="${line##* }"
    new="${parent}${child}"
    [[ -d $new ]] && touch "$new"/"$child".md
done < <(inotifywait --quiet --monitor --event CREATE,ISDIR /home/tim/test)

You can send it to the background :

./dir_event.sh &

Or perhaps use nohup or disown if you want :

nohup ./dir_event.sh &
  • inotifywait --quiet --monitor --event CREATE,ISDIR /home/tim/test is the command to monitor the file system events on directory /home/tim/test, we are only interested in CREATE and ISDIR events. We are saving (as line) and then manipulating every new line indicating a relevant event as they happen. Please check man inotifywait to get more idea.

  • parent will contain the directory we are monitoring /home/tim/test in this case and child will contain the newly created directory/file. Both are achieved by using bash parameter expansion.

  • new is addition of the two to get the absolute path to the newly created entry. As CREATE event will result in creating a file too we need to make sure that new is a directory.

  • [[ -d $new ]] checks if new is a directory, if so then we have created the required file inside it.

heemayl
  • 93,925
1

Try this:

#!/bin/bash

for d in */; do
    touch $d/$d.md
done
Grammargeek
  • 2,792
0

This is what I've ended up using.

while :
do
    for dir in *; do
        if [ "$dir" != "Untitled Folder" ];
        then

            if [ "$(ls "$dir")" = '' ];
            then

                touch "$dir/$dir.md"
            fi
        fi
    done
done

Thanks to @Grammageek, his original post really helped with the for loop concept..

Tim
  • 33,500