#!/bin/ksh
#< Centre a string in a terminal window, using symbols if required
# Usage:
# centre_string.sh width symbol "string"
# e.g. centre_string.sh 20 "-" "< TEST >"
# gives ------< TEST >------
PROGNAME=`basename $0`
validate_width() {
echo "${WIDTH}" | egrep "^[0-9]+$" >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "Error: width must be an integer!" >&2
exit 2
fi
}
calculate() {
STRINGLENGTH=${#STRING}
TOTALSPACE=$(( WIDTH - STRINGLENGTH ))
if [ "${STRINGLENGTH}" -gt "${WIDTH}" ]; then
echo "Error: string longer than width!" >&2
exit 2
fi
HALFSPACE=$(( TOTALSPACE / 2 ))
if [ "$(( ${TOTALSPACE} % 2 ))" -ne "0" ]; then
# odd
LHS=$(( HALFSPACE + 1 ))
else
LHS=${HALFSPACE}
fi
RHS=${HALFSPACE}
}
print_string() {
LHSYM=`perl -e "print "%s", '${SYMBOL}'x${LHS};"`
RHSYM=`perl -e "print "%s", '${SYMBOL}'x${RHS};"`
echo "${LHSYM}${STRING}${RHSYM}"
}
if [ "$#" -ne "3" ]; then
echo "Usage: ${PROGNAME} width symbol string" >&2
exit 1
fi
WIDTH="$1"
SYMBOL="$2"
STRING="$3"
validate_width
calculate
print_string
exit 0