n8felton
2/22/2015 - 4:20 AM

echo_centered.sh

echo_centered.sh

#!/bin/bash

# This function will echo text centered horizontally within the shell window.
echo_centered () {

    # The character to be used as left/right filler.
    if [[ -n "$2" ]]; then
        FILLER="$2"
    else
        FILLER="="
    fi

    # The character(s) to be used as padding around the string.
    L_PAD=" "
    R_PAD=" "

    # The string. (Argument $1.)
    STRING="$1"

    # Get the width of the current window.
    if [[ -n "$3" ]]; then
        WIDTH="$3"
    else
        WIDTH=$(tput cols)
    fi

    # Calculate the length of the string to be displayed.
    STR_LEN=$(( ${#STRING} + ${#L_PAD} + ${#R_PAD} ))

    # Exit if the string won't fit in our window.
    if [[ $STR_LEN -gt $WIDTH ]]; then
        echo "ERROR: I can't yet center strings greater than the available width."
    else

        STRING="${L_PAD}${STRING}${R_PAD}"

        # Add FILLER to the left and right side of STRING.
        for (( i = 0; i < $(( ( WIDTH - STR_LEN ) / 2 )); i++ )); do
            STRING="${FILLER}${STRING}${FILLER}"
        done

        # If the STRING length is odd, add one more FILLER on the right.
        if [[ $(( ( WIDTH - STR_LEN ) % 2 )) -ne 0 ]]; then
            STRING="${STRING}${FILLER}"
        fi

        echo "$STRING"

    fi
}

echo_centered "DO NOT EDIT BELOW THIS LINE"
# ======================== DO NOT EDIT BELOW THIS LINE =========================

echo_centered "the following section is a work in progress" "#" 80
# ################ the following section is a work in progress #################

echo_centered "Hello world" " " 60
#                        Hello world

echo_centered "Hello world" " " 40
#              Hello world

echo_centered "Hello world" " " 20
#    Hello world

exit 0