Skip to content

Instantly share code, notes, and snippets.

@Neo-Desktop
Last active December 1, 2022 20:50
Show Gist options
  • Save Neo-Desktop/b341b5fd24e84911a0e76e9281b09182 to your computer and use it in GitHub Desktop.
Save Neo-Desktop/b341b5fd24e84911a0e76e9281b09182 to your computer and use it in GitHub Desktop.
Bash function to vertically/horizontally center text
#!/bin/bash
##
# Horizontaly centers a line of text
#
# @method hcenter
# @param string $text - splat of text
#
##
function hcenter {
text=$@
cols=`tput cols`
IFS=$'\n'$'\r'
for line in $(echo -e $text); do
line_length=`echo $line | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" | wc -c`
half_of_line_length=`expr $line_length / 2`
is_odd=`expr $line_length % 2 == 1`
half_of_line_length=`expr $half_of_line_length + $is_odd`
center=`expr \( $cols / 2 \) - $half_of_line_length`
spaces=""
for ((i=0; i < $center; i++)) {
spaces+=" "
}
echo "$spaces$line"
done
}
##
# Vertically centers a line of text
#
# @method vcenter
# @param string $text - splat of text
#
##
function vcenter {
text=$@
rows=`tput lines`
text_length=`echo -e $text | wc -l`
half_of_text_length=`expr $text_length / 2`
center=`expr \( $rows / 2 \) - $half_of_text_length`
lines=""
for ((i=0; i < $center; i++)) {
lines+="\n"
}
echo -e "$lines$text$lines"
}
##
# Horizontally and Verticallly centers a line of text
#
# @method center
# @param string $text - splat of text
#
##
function center {
text=$@
vcenter "`hcenter $text`"
}
#!/bin/bash
source center_func.sh
center "oh\n yea\n dude\n this\n is\n crazy\n and\n this\n is\n crazier"
@niksingh710
Copy link

how can i pass output of figlet command .
BTW very nice script.

@Neo-Desktop
Copy link
Author

Neo-Desktop commented Jul 10, 2022

how can i pass output of figlet command . BTW very nice script.

figlet probably won't work as intended - but something like this may work

$ hcenter `figlet -c cowsay test`

It's been a very long time since I worked with these fucntions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment