简体   繁体   中英

How to update text of a specific line on terminal?

I'm programming bash script but there is a problem that is how to update text of a specific line.

I've tried using clear command. But using clear is refresh all lines on terminal but i want to refresh specific line. Like under

===============

TIME: 20:35

===============

I want to refresh only "20:35" part, without "=====" and "TIME:".

1)

while true
do
clear
echo "
===============
TIME: $(date +%H:%M)
==============="
done

2)

function TIME_RE(){
while true
do
printf "TIME: $(date +%Y.%m.%d) ($(date +%H:%M:%S)) \r"
done
}
echo "
===============
TIME: $(TIME_RE)
==============="

I expected result of second is refreshing only " $(TIME_RE) " part, but it displayed nothing.

You can use ANSI escape codes to move cursor position, or save and restore cursor position. For example, using the cursor up sequence:

while true; do
echo -e "
===============
TIME: $(date +%Y.%m.%d) ($(date +%H:%M:%S))
===============
\e[5A"
sleep 1
done

Notes:

  • you need echo's -e option to let you print escape sequences.

  • the "\\e[5A" is the sequence to move 5 lines up.

  • add something like "sleep 1" as delays to avoid burdening the system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM