github gitlab twitter linkedin email rss
Create directories and files with bash
Feb 7, 2017
2 minutes read

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.


#! /usr/bin/env bash

set -e
set -u

for testdir in "[email protected]"; do
    echo "create directory '$testdir'"
    mkdir -p $testdir
    for i in {1..3}; do
        counter=$(printf %02d $i)
        echo "create file '$testfile'"
        echo "def test_sth(): assert True" > $testfile

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/'
create file 'foobar/'
create file 'foobar/'
create directory 'hello/world'
create file 'hello/world/'
create file 'hello/world/'
create file 'hello/world/'

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

$ tree
├── create_files.bash
├── foobar
│   ├──
│   ├──
│   └──
└── hello
    └── world

3 directories, 7 files

Maybe you find this useful too, please let me know on Twitter! 😀

Back to posts