Bash - Automating creation of test files I'm in the process of understanding shell scripting - this is my simple code for adding test files for python unittest
I'm looking for best practice pointers, variable naming, and of course comments on structure and readability.
EDIT: Script is called by, for example
./create_tests.sh math tensor_add

dir_name=&quot;$1&quot;
file_name=&quot;$2&quot;
test_dir=&quot;test/${dir_name}&quot;
file_in_dir=&quot;${test_dir}/${file_name}.py&quot;

addFile() {
    if [[ -f &quot;${file_in_dir}&quot; ]]
    then
        echo &quot;File already exists in directory, exiting.&quot;
        exit 0
    else
        touch &quot;${file_in_dir}&quot;
    fi
}

if [[ -d &quot;${test_dir}&quot; ]]
then
    echo &quot;Directory already exists, adding the file to this directory.&quot;
    addFile
else
    echo &quot;Directory and __init__.py created.&quot;
    mkdir &quot;${test_dir}&quot;
    touch &quot;${test_dir}/__init__.py&quot;
    addFile
fi
Add a shebang.
Keep naming consistent, I personally prefer and follow Google's style guide; you may use a different guide if available.
Try to make your script POSIX compliant, for a wider target reach (no need to rely on [[ expression from bash)
Define a function to create the test directory.
Use shellcheck.
The echo &quot;Directory and __init__.py created.&quot; should happen after the creation has happened.
Use mkdir -p to allow for nested directories to also be created (if needed).
Let script throw error and stop as early as possible on errors. This is achieved with set -e.


Together:
#!/bin/sh

set -e

dir_name=&quot;$1&quot;
file_name=&quot;$2&quot;
test_dir=&quot;test/${dir_name}&quot;
file_in_dir=&quot;${test_dir}/${file_name}.py&quot;

add_file() {
    if test -f &quot;${file_in_dir}&quot;
    then
        echo &quot;File already exists in directory, exiting.&quot;
        exit 0
    else
        touch &quot;${file_in_dir}&quot;
    fi
}

create_dir() {
    mkdir -p &quot;${test_dir}&quot;
    touch &quot;${test_dir}/__init__.py&quot;
    echo &quot;Directory and __init__.py created.&quot;
}

[ ! -d &quot;${test_dir}&quot; ] &amp;&amp; create_dir &quot;${test_dir}&quot;

add_file

The chunk of variable declarations (dir_name, file_name etc.) could also be localised to functions.