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.

BASH prompt galore

Here’s the latest result of trying to make a BASH prompt which might be useful if you use chroot, ssh, su or git:

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]
then
    debian_chroot=$(cat /etc/debian_chroot)
fi

chroot='${debian_chroot:+($debian_chroot)}'
PS1="$chroot"

# Color support detection from Ubuntu
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null
then
    reset='\[\e[0m\]'
    red='\[\e[1;31m\]'
    green='\[\e[1;32m\]'
    orange='\[\e[1;33m\]'
    blue='\[\e[1;34m\]'
fi

# Red user if root, orange if su
if [ "$USER" = "root" ]
then
    PS1="$PS1$red"
elif [ -n "$SUDO_USER" ]
then
    PS1="$PS1$orange"
else
    PS1="$PS1$green"
fi
PS1="${PS1}\u${reset}@"

# Red host if SSH
if [ -n "$SSH_CONNECTION" ]
then
    PS1="$PS1$red"
else
    PS1="$PS1$green"
fi
PS1="${PS1}\h${reset}:${blue}\w${reset}"

# Git branch
if [ "$(type -t __git_ps1)" = "function" ]
then
    PS1="${PS1}\$(__git_ps1 ' (%s)')"
fi

# PS1 end
if [ "$USER" = "root" ]
then
    separator='#'
else
    separator='$'
fi
PS1="${PS1}${separator} "

Example session (if the above is in ~/.bashrc or /etc/bash.bashrc on both hosts):

my_user@local_hostname:~$ cd git-repos/project/
my_user@local_hostname:~git-repos/project (master)$ sudo -u other_user bash
other_user@local_hostname:~git-repos/project (master)$ ssh third_user@other_hostname
third_user@other_hostname:~$ exit
other_user@local_hostname:~/Desktop/images$ exit
my_user@local_hostname:~/Desktop/images$