BASH / Bourne Shell which outputs its own documentation

I love Python docstrings – It’s a great application of the DRY principle. The excellent Advanced Bash-Scripting Guide has an example which does something similar, but it embeds the documentation in a variable in the middle of the code. This makes it less readable and findable than ordinary comments, and leads to duplication if you want to have the same documentation as a comment for other developers. Here’s a very simple solution, which I’m sure can be improved to fit your documentation style. It simply prints all non-empty lines from the start of the file:

usage()
{
    # Print documentation until the first empty line
    while read line
    do
        if [ ! "$line" ]
        then
            exit 64
        fi
        echo "$line"
    done < $0
}

A bit of detail: The exit code is from /usr/include/sysexits.h on Linux, which seems to be the standard, and < $0 passes the contents of the current file to the while loop.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s