Freitag, 7. Februar 2014

Embedding Online Help Inside Shell Script

I recently posted an article on how to document a shell script using the Plain Old Documentation (POD) format and then produce a nice looking HTML document from that.

Based on that idea I want to show you this time how to utilize the in-line POD documentation to generate a professionally looking online help. In detail, that is a man page which is being displayed if the user provides the argument help to the shell script (or any other argument you choose for that purpose).

Since the last post already explained all the required background on embedding POD in shell script, I start straight with the example code:
#!/bin/bash

## =head1 Name
##
## pod_example.sh - A Demo Script
##
## =head1 Synopsis
##
## pod_example.sh [help]
##
## =head1 Description
##
## This script demonstrates embedding online help
## into a shell script.
##
## =head1 Details
##
## The script calls two functions in the following order:
##
## =over
##
## =item *
##
## firstFunction 
##
## =item *
##
## secondFunction
##
## =back
##
  
SCRIPT_VERSION="0.1"

firstFunction() {
    echo "i'm the first function"
}

secondFunction() {
    echo "i'm the second function"
}

showHelp() {
     local podData=$(cat $0 | egrep '^##' | sed 's/^##\s\?//g')

     if [ "${podData}" ]; then
         echo "${podData}" |                             \
         pod2man --center="A Demo Script"                \
                 --date="$(date +%D)"                    \
                 --name="Demo"                           \
                 --release="Version ${SCRIPT_VERSION}" | \
         man -l -
     fi
}

# main part
if [ "$1" = "help" ]; then
    showHelp
    exit
fi

firstFunction
secondFunction
This example script starts with the documentation in POD format. Since the first line of function showHelp extracts the POD documentation from the shell script it is up to you where to place your documentation - as long as your POD data starts with double hash (#). Again, see the previous post for details of the first line of showHelp.

The interesting and new things are happening from line 47 on. Here, we send the plain POD data to the converter pod2man which is part of the standard perl package. The optional arguments supply the text surrounding the online help (see screenshot below).

To no surprise the man data generated is feed into the man program via the standard input (line 52). Option "-l" enables the support of local man pages, "-" indicates that man data is coming from STDIN.

That's the whole magic - made possible by the beauty of Unix pipes. The result of calling "pod_example.sh help" should look very familiar to any Unix nerd:



Keine Kommentare:

Kommentar veröffentlichen