"Standardized" docstring/self-documentation of bash scripts

The "File Header" section of Google's Shell Style Guide is one way to add a 'docstring' to your bash scripts.

Basically, the answer is to use #, rather than quotes like you would with Python.


There is no standard for docstrings for bash. It's always nice to have man pages though (eg. https://www.cyberciti.biz/faq/linux-unix-creating-a-manpage/), or info pages (https://unix.stackexchange.com/questions/164443/how-to-create-info-documentation).


You can do this for Bash easily, it is a little more tricky if you need to ensure compatibility with POSIX only shells like /bin/sh or primarily busybox systems like Alpine.

The Linux Documentation Project has some great examples.

http://tldp.org/LDP/abs/html/here-docs.html

Yet another twist of this nifty trick makes "self-documenting" scripts possible.

Example 19-12. A self-documenting script

#!/bin/bash
# self-document.sh: self-documenting script
# Modification of "colm.sh".

DOC_REQUEST=70

if [ "$1" = "-h"  -o "$1" = "--help" ]     # Request help.
then
  echo; echo "Usage: $0 [directory-name]"; echo
  sed --silent -e '/DOCUMENTATIONXX$/,/^DOCUMENTATIONXX$/p' "$0" |
  sed -e '/DOCUMENTATIONXX$/d'; exit $DOC_REQUEST; fi


: <<DOCUMENTATIONXX
List the statistics of a specified directory in tabular format.
---------------------------------------------------------------
The command-line parameter gives the directory to be listed.
If no directory specified or directory specified cannot be read,
then list the current working directory.

DOCUMENTATIONXX

if [ -z "$1" -o ! -r "$1" ]
then
  directory=.
else
  directory="$1"
fi  

echo "Listing of "$directory":"; echo
(printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \
; ls -l "$directory" | sed 1d) | column -t

exit 0

Using a cat script is an alternate way of accomplishing this.

DOC_REQUEST=70

if [ "$1" = "-h"  -o "$1" = "--help" ]     # Request help.
then                                       # Use a "cat script" . . .
  cat <<DOCUMENTATIONXX
List the statistics of a specified directory in tabular format.
---------------------------------------------------------------
The command-line parameter gives the directory to be listed.
If no directory specified or directory specified cannot be read,
then list the current working directory.

DOCUMENTATIONXX
exit $DOC_REQUEST
fi

A slightly more elegant example using functions to handle the documentation and error messages.

#!/bin/sh

usage() {
cat << EOF
Usage: 
  $0 [-u [username]] [-p]
  Options:
    -u <username> : Optionally specify the new username to set password for.  
    -p : Prompt for a new password.
EOF
}

die() {
  echo
  echo "$1, so giving up.  Sorry."
  echo
  exit 2
}

if [ -z "$USER" ] ; then
  die "Could not identify the existing user"
fi

if $PSET ; then
  passwd $USER || die "Busybox didn't like your password"
fi

https://github.com/jyellick/mficli/blob/master/util/changecreds.sh