Create directories and files with bash

2 min read #bash #helper

Sometimes, I find it quite handy to use a bash script to generate a bunch of files spread across a number of directories to develop against. Imagine you are working on a pytest plugin that modifies reporting and want to test it with a simple directory structure. Or maybe you want to demo a feature during a conference talk?

While I generally tend to favor Python for scripts like this (and many other things ๐Ÿ˜), I occasionally use the following bash script.

Mostly when I don’t really care about the files’ contents.

create_files.bash

#! /usr/bin/env bash

set -e
set -u

for testdir in "$@"; do
    echo "create directory '$testdir'"
    mkdir -p $testdir
    for i in {1..3}; do
        counter=$(printf %02d $i)
        testfile=$testdir/test_${testdir##*/}_$counter.py
        echo "create file '$testfile'"
        echo "def test_sth(): assert True" > $testfile
    done
done

We need to change the permissions on this file to make it executable:

$ chmod +x create_files.bash

Now we can call it with a number of arguments for the directories that we would like to create:

$ ./create_files.bash foobar hello/world

It will then print the following output:

create directory 'foobar'
create file 'foobar/test_foobar_01.py'
create file 'foobar/test_foobar_02.py'
create file 'foobar/test_foobar_03.py'
create directory 'hello/world'
create file 'hello/world/test_world_01.py'
create file 'hello/world/test_world_02.py'
create file 'hello/world/test_world_03.py'

And using the tree tool, we can now inspect the directory structure:

$ tree
.
โ”œโ”€โ”€ create_files.bash
โ”œโ”€โ”€ foobar
โ”‚ย ย  โ”œโ”€โ”€ test_foobar_01.py
โ”‚ย ย  โ”œโ”€โ”€ test_foobar_02.py
โ”‚ย ย  โ””โ”€โ”€ test_foobar_03.py
โ””โ”€โ”€ hello
    โ””โ”€โ”€ world
        โ”œโ”€โ”€ test_world_01.py
        โ”œโ”€โ”€ test_world_02.py
        โ””โ”€โ”€ test_world_03.py

3 directories, 7 files

Maybe you find this useful too, please let me know on Twitter! ๐Ÿ˜€