When I started to write bash scripts, I used to write a documentation in the script, and write a method to echo another documentation fur the user. It was a bit annoying to have redundant text and keep both up to date. So I wrote below function to print out what I put into the header of the script.
The following is the function I have created for printing out the script header. All the samples on this page where extracted from the MetricCollector. sh script you can find here >> https://github.com/xresch/PENG_Toolbox/blob/master/BashScripts/MetricCollector/metricCollector.sh
############################################################
# Print documentation written in the bash file.
############################################################
print_docu(){
SOURCE_PATH="${BASH_SOURCE[0]}"
cat "${SOURCE_PATH}" | gawk '
BEGIN{
isLineInDocumentHead="before";
print " ";
}
{
if ( match($0,"^#############") ){
if ( isLineInDocumentHead == "before" ){
isLineInDocumentHead="between";
next;
}else {
if ( isLineInDocumentHead == "between"){
isLineInDocumentHead="end";
}
}
}
if ( isLineInDocumentHead == "between"){
sub("^#","", $0)
print ;
}
}
'
exit 1
}
In your script you will write a header like this:
#!/bin/bash
###########################################################################################
# Author: Reto Scheiwiller, 2016
# Licence: MIT License
# Repository: https://github.com/xresch/PENG_Toolbox
#
# Metric Collector
# -----------------
# Collects server and process information from various tools and creates charts with the
# data. The script was tested on GNU/Linux with gnuplot 4.4.
# For the script to work you have to set the variable "JAVA_HOME" to a valid location.
# All arguments are optional, if "-p" is not used no collections from a process will be done.
#
###########################################################################################
All the text between the two “##########…” lines will get printed, without the leading #. The result will look like this:
Author: Reto Scheiwiller, 2016
Licence: MIT License
Repository: https://github.com/xresch/PENG_Toolbox
Metric Collector
-----------------
Collects server and process information from various tools and creates charts with the
data. The script was tested on GNU/Linux with gnuplot 4.4.
For the script to work you have to set the variable "JAVA_HOME" to a valid location.
All arguments are optional, if "-p" is not used no collections from a process will be done.
You can add a check if the script has any arguments passed to it, if not you can print out the documentation:
# Check if there is at least one argument present, else print help
if [ "$#" -eq 0 ]
then
print_docu
fi
Additionally you can add this function to the script options. The following example binds it to the option “-h”:
while getopts "h?" option
do
case $option in
h) print_docu;;
?) echo "unkown argument: $option";
esac
done