c++linuxanimationterminallibraries

Making animated text in linux terminal


I would like to make animated text inside of the Linux terminal.

By 'animated', I mean a single character constantly changing to make it form some sort of animation. What I want is something like this:

|  # First second
/  # One second after previous frame
-  # One second after previous frame
|  # One second after previous frame
-  # One second after previous frame
\  # Last frame, skip back to top

...so it creates a line that appears to be spinning.

I am already quite aware of the method using clear, however this does not suit my needs.

clear removes all text, including previous text. I do not want this. I have seen plenty of animations in the terminal window not doing this (for example the loading bar shown using apt install), however, I have failed to reproduce.

How would I make an animation, such as a loading bar using the Linux terminal? If a library, I would prefer it being built for C++.


Solution

  • Using tput is the key here which is part of ncurses.

    This is the sample script which I wrote:-

    #!/usr/bin/env bash
    
    clear  # Let clear the screen first
    
    echo " Starting the spinning wheel.."
    echo " Press 'q' or 'Q' to stop it.."
    
    # to set the cursor position on terminal on row 2 column 1
    tput cup 2 1
    
    while true; do
       echo '|'
       sleep 1
       tput cup 2 1  # reset cursor position
    
       echo '/'
       sleep 1
       tput cup 2 1  # reset cursor position
       echo '-'
    
       sleep 1
       tput cup 2 1  # reset cursor position
       echo '\'
    
       sleep 1
       tput cup 2 1  # reset cursor position
       echo '|'
    
       tput cup 2 1  # reset cursor position
      # -t for timeout, -N to except only 1 character
       read -t 0.25 -N 1 ch
       if [[ $ch = "q" ]] || [[ $ch = "Q" ]]; then
           # The following line is for the prompt to appear on a new line.
            echo
            break
       fi
    
    done
    

    It's like a basic version. You can refine it further. You can find the script here as well:- https://github.com/uv3003/uv/blob/main/rolling_pointer.sh

    Regards, Yuvraj