-1

I really liked echo -ne for its simplicity, but it doesnt work for me, so i decided to use the "Pro" version of echo – "Printf"


I want to make a script which shows important information in real time and looping clear command to refresh the screen is just stupid and RAM consuming thing. Suppose i have 3 important variables ($var_1 $var_2 $var_3) which i want to display on different lines and refresh every second (variables are both integers and text)

#!/bin/bash/
while :
do
printf "%s\n\r %s\n\r %s\n\r" $var_1 $var_2 $var_3
sleep 1
done

Output

10.2324 #var_1
213 #var_2
120 #var_3
10.2324 #var_1
213 #...
150
10.2323
213
170

I tried multiple different ways and searching on different forums, but I didn't find the answer. How can I print 3 variables on 3 different lines and update them every second?

1 Answers1

1

\r only moves the cursor to the beginning of the current line, whereas you need the cursor to move up three lines as well. You need to use a different escape code. Assuming the use of ANSI escape codes by your terminal, you can use

while :; do
  printf '%s\n' "$var_1" "$var_2" "$var_3"
  printf '\033[3A'  # move up 3 lines
  sleep 1
  ((var_1++, var_2++, var_3++))  # Simple changes to demonstrate
done

This prints each variable on a separate line, then moves the cursor back to the beginning before sleeping.

chepner
  • 497,756
  • 71
  • 530
  • 681