Sometimes we might want to print some text in Bash and we might want it to be centered to the centre of the terminal. It is a cheap way how we can increase clarity of output of our script and make it look much more attractive.
The whole magic is hidden in a program called tput
.
To get number of rows and cols of current terminal, we need just two simple shell substitutions:
TERM_ROWS="$(tput rows)"
TERM_COLS="$(tput cols)"
For centering our arbitrary text to the middle of the terminal, we actually only need to know
the value of TERM_COLS
. So we are already ready to go!
Without further comments, I present here a simple bash function called print_centered
,
which awaits one or two arguments. The first argument is a string to be centered,
the second argument is a character that should fill the rest of the line.
Default filling character is -
function print_centered {
[[ $# == 0 ]] && return 1
declare -i TERM_COLS="$(tput cols)"
declare -i str_len="${#1}"
[[ $str_len -ge $TERM_COLS ]] && {
echo "$1";
return 0;
}
declare -i filler_len="$(( (TERM_COLS - str_len) / 2 ))"
[[ $# -ge 2 ]] && ch="${2:0:1}" || ch=" "
filler=""
for (( i = 0; i < filler_len; i++ )); do
filler="${filler}${ch}"
done
printf "%s%s%s" "$filler" "$1" "$filler"
[[ $(( (TERM_COLS - str_len) % 2 )) -ne 0 ]] && printf "%s" "${ch}"
printf "\n"
return 0
}
And this is how it can look in real usage:
------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
Building local Jekyll project in: /home/user/jekyll/example.com
------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
Configuration file: /home/user/jekyll/example.com/_config.yml
Source: /home/user/jekyll/example.com
Destination: /home/user/jekyll/example.com/_site
Incremental build: disabled. Enable with --incremental
Generating...
done in 0.21 seconds.
Auto-regeneration: disabled. Use --watch to enable.
The first five lines are printed by print_centered
function. The first two
and last two are printed using command
print_centered "-" "-"
which centers one -
at the middle of the terminal and fills the rest of line
with the same character - an easy way to achieve a "horizontal bar".
If you have any questions about this, feel free to ask in comments.
This looks great, but how do I use it in a script? Do Isource
the file and then callprint_formatted
? If so, how? For me this results in a "No parameter given" error.I found this to work:
This will result in:
Obviously, the spaces surrounding 'Test Text' are optional, and all other values can be altered. The only thing I'm having issues with is adding color. If you do add color, it messes with the length set by
-n