Skip to content

Instantly share code, notes, and snippets.

@n8felton
Forked from homebysix/gist:301a7a2e31b02ab7c45c
Last active December 23, 2021 15:58
Show Gist options
  • Save n8felton/6944f0532f2cbb04d363 to your computer and use it in GitHub Desktop.
Save n8felton/6944f0532f2cbb04d363 to your computer and use it in GitHub Desktop.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment