5

How do I output a string in the bottom right corner of the terminal?

Petr Skocik
  • 28,816

2 Answers2

9
string=whatever
stty size | {
  read y x
  tput sc # save cursor position
  tput cup "$((y - 1))" "$((x - ${#string}))" # position cursor
  printf %s "$string"
  tput rc # restore cursor.
}

That assumes all characters in $string are one cell wide (and that $string doesn't contain control characters (like newline, tab...)).

If your string may contain zero-width (like combining characters) or double-width ones, you could use ksh93's printf's %Ls format specifier that formats based or character width:

string='whatéver'
# aka string=$'\uFF57\uFF48\uFF41\uFF54\uFF45\u0301\uFF56\uFF45\uFF52'
stty size | {
  read y x
  tput sc # save cursor position
  tput cup "$((y - 1))" 0 # position cursor
  printf "%${x}Ls" "$string"
  tput rc # restore cursor.
}

That would erase the leading part of the last line though.

  • I try the first one in zsh and yash but it did not work. – cuonglm Nov 23 '15 at 16:02
  • @cuonglm, did you try it at the prompt of an interactive shell and the comments caused problems? Also note that zsh and yash erase the region below their prompt. – Stéphane Chazelas Nov 23 '15 at 16:14
  • @StéphaneChazelas: I removed all the comments, start with zsh -f, and nothing printed. The same problem with yash. – cuonglm Nov 23 '15 at 16:19
  • @cuonglm, nothing printed, or printed but then removed by your interactive shell's prompt doing a clear to end of screen (as yash and zsh do)? – Stéphane Chazelas Nov 23 '15 at 16:25
  • @StéphaneChazelas: I'm not sure. If I use tput cup "$((y))" "$((x))", then I got only the w character at the right corner. – cuonglm Nov 23 '15 at 16:57
  • @StéphaneChazelas: Can you re-proceduce my issue? – cuonglm Nov 24 '15 at 11:38
  • @cuonglm, as I said, it's you shell erasing the bottom part of the screen. add a sleep 2, at the end of that code and you'll see the text displayed there. But after that your shell will erase it. Nothing you can do about it. With those shells, the part bellow the prompt belongs to them. – Stéphane Chazelas Nov 24 '15 at 11:48
  • @StéphaneChazelas: Thanks, get it now. Is this behavior documented else where in the doc? – cuonglm Nov 24 '15 at 11:56
  • Those shells use and reuse the space below the prompt for messages and completion, the simplest way to handle it (and produces minimal tty i/o) is to clear the bottom end of the screen. – Stéphane Chazelas Nov 24 '15 at 12:18
4
tput cup $(tput lines) $[$(tput cols)-16]
printf "string"

or

tput cup $[$(tput lines)-1] $[$(tput cols)-16]
printf "string"

where 16 is the length that you want to reserve for the string.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Yunus
  • 1,684