1

I write the follow script, to print one name to the center of my terminal. In the last command, when i use numbers, everything is ok. However, when i use variables x_center and y_center i have a trouble...

#!/bin/sh
`clear`

num_lines=`tput lines`
num_cols=`tput cols`

echo "Enter your Name: "
read name

length_name=`echo $name | wc -c `
length_name=`expr $length_name - 1`

offset=`expr $length_name / 2`
x_center=`expr $num_lines / 2`
y_center=`expr $num_cols / 2`
y_center=`expr $offset + $x_center`

printf "%s = %d, %s = %d\n" "X" "$x_center" "Y" "$y_center"

echo -n "\033[$x_center;$y_centerf" $name
Panagiotis
  • 511
  • 8
  • 26
  • Why have you tagged this as `bash` when you seem to avoid many of the useful features that it offers like shell arithmetic and string length functions? – Mark Setchell May 31 '15 at 18:35

1 Answers1

3

That last line looks as if it was intended to move the cursor:

echo -n "\033[$x_center;$y_centerf" $name

However, it will not because this fragment $y_centerf is not defined, and does not end with the appropriate final character of the control sequence. Rather than do this, one can do

tput cup $x_center $y_center
echo "$name"

The cup means "cursor position", and can be found in the terminfo(5) manual page. CUP likewise can be found in XTerm Control Sequences. The fragment indicated likely was copied from some example using the similar HVP:

CSI Ps ; Ps f
      Horizontal and Vertical Position [row;column] (default =
      [1,1]) (HVP).

Curly braces could repair it, e.g., ${y_center}f), but (a) HVP is less common than CUP and (b) using hard-coded escapes when tput is already working is problematic.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105