#!/bin/bash
# script: bash2html
# purpose: take input and convert all bash escape codes to html
# author: Florian Loeffler
# site: http://www.geek-blog.de/projekte/bash2html
# copyright: licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
# (see http://creativecommons.org/licenses/by-nc-sa/3.0/)
# version: 0.1
# global variables
SCRIPTNAME=`basename $0 .sh`
SCRIPTDIR=`dirname $0`
MIN_ARGS=1
EXIT_SUCCESS=0
EXIT_FAILURE=1
EXIT_ERROR=2
EXIT_BUG=10
# preset defaults
INPUT_FILE=$1
OUTPUT_FILE="`basename $INPUT_FILE 2>/dev/null`.html"
FILTER_FILE="$SCRIPTDIR/bash2html.sed"
# pre-initialization of option variables with defaults
VERBOSE_FLAG=0
# functions
function usage {
echo -ne "Purpose: take input and convert all bash escape codes to html\n\n" >&2
echo -ne "Usage: $SCRIPTNAME -i INPUT_FILE [-o OUTPUT_FILE] [-h] [-v] [-f FILTER_FILE]\n" >&2
echo -ne "Usage: $SCRIPTNAME INPUT_FILE [-o OUTPUT_FILE] [-h] [-v] [-f FILTER_FILE]\n\n" >&2
echo -ne "\t-h\t\tdisplay this help\n" >&2
echo -ne "\t-v\t\tbe verbose (unused so far)\n" >&2
echo -ne "\t-i FILENAME\tfile containing the input text\n" >&2
echo -ne "\t-o FILENAME\tfile to write the converted text to\n\t\t\tIf OUTPUT_FILE is not specified it defaults to 'INPUT_FILE.html'.\n\t\t\tExisting files are NOT overwritten.\n" >&2
echo -ne "\t-f FILENAME\tfile containing the sed filter script to use for the conversion\n\t\t\tThis defaults to 'bash2html.sed'.\n" >&2
if [ $# = 1 ]
then
exit $1
else
exit $EXIT_FAILURE
fi
}
# test minimal number of arguments
if (( $# < $MIN_ARGS ))
then
echo "Too few arguments." >&2
usage $EXIT_ERROR
fi
# parse arguments and set flags if necessary
while getopts ':vhi:o:f:' OPTION
do
case $OPTION in
v) # verbosity
VERBOSE_FLAG=1
;;
h) # help
usage $EXIT_SUCCESS
;;
i) # input file
INPUT_FILE=$OPTARG
OUTPUT_FILE="$INPUT_FILE.html"
;;
o) # output file
OUTPUT_FILE=$OPTARG
;;
f) # file containing the sed filter script
FILTER_FILE=$OPTARG
;;
\?) # unknown option
echo "Unknown option \"-$OPTARG\"." >&2
usage $EXIT_ERROR
;;
:) # missing argument for an option
echo "Option \"-$OPTARG\" is missing an argument." >&2
usage $EXIT_ERROR
;;
*) # this should not be reached (because \? catches unknown options)
echo "Option not implemented." >&2
usage $EXIT_BUG
;;
esac
done
shift `expr $OPTIND - 1`
# do stuff ;)
if [ -e $OUTPUT_FILE ]; then
echo -ne "WARNING!! File '$OUTPUT_FILE' already exists. I won't overwrite it.\n"
exit $EXIT_FAILURE
fi
echo -ne "Using sed filter script from '$FILTER_FILE'.\n"
echo -ne "Processing..."
OUTPUT_TEXT=`sed -n -f $FILTER_FILE $INPUT_FILE`
echo -ne "done.\n\n"
echo "$OUTPUT_TEXT" > $OUTPUT_FILE
echo "$OUTPUT_TEXT"
echo -ne "\nResult also saved to '$OUTPUT_FILE'.\n"
echo -ne "done.\n"
exit $EXIT_SUCCESS