Last Updated: March 02, 2016
·
439
· hackebrot

Create a Bunch of Files with Bash

Good documentation uses examples to illustrate how software works. Occasionally you want to create a bunch of files for demonstration purposes.

This is how you can programmatically create files with a simple bash script.

Create Script File

Create a new script file foobar.sh with the following content:

#! /usr/bin/env bash
set -e
set -u
set -x

for testdir in foobar hello/world example
do
    mkdir -p $testdir
    for i in {1..3}
    do
        counter=$(printf %02d $i)
        testfile=$testdir/test_${testdir##*/}_$counter.py
        echo "def test_sth(): assert True" > $testfile
    done
done

We use a nested for-loop to create three directories each of which containing three numbered python modules.

Run Bash Script

Once you make the script executable (via chmod +x foobar.sh), you can run it as follows:

$ ./foobar.sh

Result

There we go!

.
├── example
│   ├── test_example_01.py
│   ├── test_example_02.py
│   └── test_example_03.py
├── 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

1 Response
Add your response

It's a nice example, thanks!

over 1 year ago ·