This chapter we will discuss the layout of the script output and how the user interact with the script.

 

Tput

Tput is a command which allows you to control the cursor on the terminal and the format of content that is printed.

#!/bin/bash
# Print message in center of terminal

cols=$( tput cols )
rows=$( tput lines )

message=$@

input_length=${#message}

half_input_length=$(( $input_length / 2 ))


middle_row=$(( $rows / 2 ))
middle_col=$(( ($cols / 2) - $half_input_length ))

tput clear

tput cup $middle_row $middle_col
tput bold
echo $@
tput sgr0
tput cup $( tput lines ) 0

Break it down:

  • Line 4tput cols will tell us how many columns the terminal has.
  • Line 5tput lines will tell us how many lines (or rows) the terminal has.
  • Line 7 – Take all the command line arguments and assign them to a single variable message.
  • Line 9 – Find out how many characters are in the string message. We had to assign all the input values to the variable message first as ${#@} would tell us how many command line arguments there were instead of the number of characters combined.
  • Line 11 – We need to know what 1/2 the length of the string message is in order to center it.
  • Lines 13 and 14 – Calculate where to place the message for it to be centered.
  • Line 16tput clear will clear the terminal.
  • Line 18tput cup will place the cursor at the given row and column.
  • Line 19tput bold will make everything printed to the screen bold.
  • Line 20 – Now we have everything set up let’s print our message.
  • Line 21tput sgr0 will turn bold off (and any other changes we may have made).
  • Line 22 – Place the prompt at the bottom of the screen.

 

Input flexibility

We should always put the convenience of the end user at the first place, and we can achieve this in a few ways such as using sed command.

If we want to format 2017/11/28, 2017:11:28, and 2017-11-28 into 2017-11-28, we can write a script date_format.sh:

#!/bin/bash
clean_date=$( echo $1 | sed 's/[ /:\^#]/-/g' )
echo $clean_date

Then test it by command:

./date_format.sh 2013:11:22

2013-11-22