Bash – How to scroll up the cursor in terminal in order to print a string

bashterminal

Here I want something like the way aircrack-ng does to display text in the terminal screen, or like matrix scripts … !

For example, if my terminal screen already contains 4 lines, I want to update the 1st of those first lines in its place, and same for other lines … (using bash)

To be more precise, I want a script like the following:

#!/bin/bash
while :
  do
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
    # without using clear cmd, next cycle line1 should be printed
    # in line1 place not in a new line , and same for other lines
  done

Best Answer

On terminals that support it, you can use tput sc to save the cursor position and tput rc to restore it:

i=0
tput sc
while sleep 1; do
  tput rc
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
done

output

You can save those escape sequences in a variable to avoid having to invoke tput every time:

rc=$(tput rc) ||
  echo >&2 "Warning: terminal doesn't support restoring the cursor"
...
printf '%s\n' "${rc}line1..."

On the rare terminals that don't support it, you can always use cursor positioning sequences,

while sleep 1; do
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
  echo "line$((i=i+1))"
  tput cuu 4 # or up=$(tput cuu1); printf %s "$up$up$up$up"
done

See the terminfo man page in section 5 (if your system ships with ncurses) for more details.