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:

    # Print documentation until the first empty line
    while read line
        if [ ! "$line" ]
            exit 64
        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.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s