patternbashModerate
Text centering function in bash
Viewed 0 times
textfunctionbashcentering
Problem
I wanted to center some text in my commandline application, so I came up with this function.
If you have suggestions on how to improve the code, and/or know a better way of centering text, please let me know.
centerText(){
textsize=${#1}
spacecount=$(tput cols)
spacecount=$((($spacecount-$textsize)/2))
while [ $spacecount -gt 0 ]
do
printf " "
spacecount=$((spacecount-1))
done
printf "$1"
echo
}If you have suggestions on how to improve the code, and/or know a better way of centering text, please let me know.
Solution
Since you are using printf to output the spaces, you may as well use a specific printf format for the output.
Here's a replacement function:
What it does is it identifies how long the whole output should be, by adding the text width and screen width together, then dividing by 2. That's a bit complicated to explain, but, the right-side of the text must be half-as-much-of-the-text as the middle of the screen.
For example, if the text is 10 characters, and the screen is 80, then the right side of the output must be at 45, or
If we know the right-hand side of the output, you can just make that a real printf statement:
The function above does that, by using the padded
By adding the newline escape
Here's a replacement function:
centerQ(){
textsize=${#1}
width=$(tput cols)
span=$((($width + $textsize) / 2))
printf "%${span}s\n" "$1"
}What it does is it identifies how long the whole output should be, by adding the text width and screen width together, then dividing by 2. That's a bit complicated to explain, but, the right-side of the text must be half-as-much-of-the-text as the middle of the screen.
For example, if the text is 10 characters, and the screen is 80, then the right side of the output must be at 45, or
(10 + 80) / 2If we know the right-hand side of the output, you can just make that a real printf statement:
printf "%45s" "some text!"The function above does that, by using the padded
%s format, it left-pads the output to 45 characters overall width. By adding the newline escape
\n to the printf you save the echo too.Code Snippets
centerQ(){
textsize=${#1}
width=$(tput cols)
span=$((($width + $textsize) / 2))
printf "%${span}s\n" "$1"
}printf "%45s" "some text!"Context
StackExchange Code Review Q#94449, answer score: 12
Revisions (0)
No revisions yet.