Display centered text in the screen in reverse video

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Moving the cursor with tputHomeSet the keyboard leds →

The following shell script display centered message in the screen in reverse video. The script use the tput command to calculate x and y coordinates. Create a shell script called center-message.sh:

#!/bin/bash
# Purpose: center-message.sh - Display centered text in the screen in reverse video
# Author: Vivek Gite 
# ---------------------------------------------------------------------------------
# Find out current screen width and hight
_COLUMNS=$(tput cols)
_LINES=$(tput lines)
 
# Set default message if $1 input not provided
_MESSAGE="${1:-Linux Shell Scripting Tutorial v2.0}"
 
# Calculate x and y coordinates so that we can display $MESSAGE
# centered in the screen 
x=$(( $_LINES / 2 ))
y=$(( ( $_COLUMNS - ${#_MESSAGE} )  / 2 ))
 
# Clear the screen
tput clear
 
# set x and y position
tput cup $x $y
 
# set reverse video mode
tput rev
 
# Alright display message stored in $_MESSAGE
echo "${_MESSAGE}"
 
# Just wait for user input...
read -p "" readDamKey 
 
# Start cleaning up our screen...
tput clear
tput sgr0
tput rc

Save and close the file. Run it as follows:

chmod +x center-message.sh
./center-message.sh "This is a test."
./center-message.sh

Sample outputs:

tput: putting it all together
← Moving the cursor with tputHomeSet the keyboard leds →