Skip to content

Instantly share code, notes, and snippets.

@markusfisch markusfisch/center.sh
Last active Jan 20, 2017

Embed
What would you like to do?
Center input from stdin in terminal or return 1 if it doesn't fit
#!/usr/bin/env bash
# Print n blank lines
#
# @param 1 - number of blank lines to print (default 1)
blanks() {
local I
for (( I=${1:-1}; I--; ))
do
echo
done
}
# Horizontally and vertically center input from stdin in terminal
center() {
local TMP
TMP=$(mktemp "/tmp/${0##*/}.XXXX")
local WIDTH=0 HEIGHT=0
while read -r
do
# there's wc -L on BSD
local L=${#REPLY}
(( L > WIDTH )) && WIDTH=$L
(( ++HEIGHT ))
echo "$REPLY"
done > "$TMP"
local LINES=${LINES:-$(tput lines)}
local COLUMNS=${COLUMNS:-$(tput cols)}
local SPACES=' '
while (( ${#SPACES} < COLUMNS ))
do
SPACES=$SPACES$SPACES
done
local VPAD=$(( (LINES - HEIGHT) / 2 ))
local HPAD=$(( (COLUMNS - WIDTH) / 2 ))
if (( VPAD < 0 )) || (( HPAD < 0 ))
then
return 1
fi
(( VPAD > 0 )) && blanks "$VPAD"
while read -r
do
echo "${SPACES:0:$HPAD}$REPLY"
done < "$TMP"
rm -f "$TMP"
(( VPAD > 0 )) && blanks "$VPAD"
}
if [ "${BASH_SOURCE[0]}" == "$0" ]
then
center
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.