Last active
January 20, 2017 14:16
-
-
Save markusfisch/f5e0c1013677ad98153d90e60241ad93 to your computer and use it in GitHub Desktop.
Center input from stdin in terminal or return 1 if it doesn't fit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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