Bash #4 - Bash Docstrings

Posted July 31, 2023 ‐ 2 min read

Previous post: #3.

Once of Python's nice features are docstrings, for which a help function on a module generates a nice documentation screen. Can we follow a similar technique in our bash? Yes we can!

We'll do this as an extension of the functional command relay technique.

Adding docstrings can be done by inserting special inner functions that don't execute on command execution. For example:

build() {
    __docstring__() {
	echo """<params>

        Build and work on stuff

	-j <core> - number of cores
       """
    }

    : # << your build implementation here >>
}

run() {
    __docstring__() {
	echo """<params>

        Run stuff
       """
    }

    : # << your run implementation here >>
}

We can pick this up in a new help command. Suppose we define help as such:

help() {
    doc-iter-functions() {
        local funcname
        for funcname in $(declare -F | grep \
            -Ev '^declare -fx' | sed 's/declare -f //g' | sort);
        do
            function __docstring__ () { :; }
            eval "$(type ${funcname} | awk '/function __docstring__ \(\)/,/};/')"
            if [[ "$(__docstring__)" != "" ]] ; then
                echo -n "    script ${funcname}"
                __docstring__
                echo
            fi
        done
    }

    cat << EOF
Help screen

$(doc-iter-functions)
EOF
}

Our script now has a help screen! We can view it by executing the help command:

$ ./script help
Help screen

    script build <params>

        Build and work on stuff

        -j <core> - number of cores

    script run <params>

        Run stuff

If you are not sure how these bash function translate to commands to the script, read the previous post regarding functional command relay.


Share this post
Follow author