linuxbashshell

How to hide the cursor in a terminal during a script and restore it back to normal if the command is interrupted?


So let's say I have this script that displays a little animation:

while [ condition ]
do
    echo -ne "\rfinished ᕙ( ᐕ )ᕓ "
    sleep 0.3
    echo -ne "\rfinished ᕕ( ᐛ )ᕗ "
    sleep 0.3
done

The problem is that the cursor is blinking next to the little guy dancing and this is a (minor) inconvenience to me, i would prefer if the cursor was hidden.

So I tried tput civis which does hide the cursor. The problem is that you need to run tput cnorm to take it back to normal. In my example, if I try:

tput civis
while [ condition ]
do
    echo -ne "\rfinished ᕙ( ᐕ )ᕓ "
    sleep 0.3
    echo -ne "\rfinished ᕕ( ᐛ )ᕗ "
    sleep 0.3
done
tput cnorm

This works well, unless the user Ctrl-Cs out of my program, which will cause them to have an invisible cursor, which is really annoying.

I tried to run the script like this:

./script || tput cnorm

but it didn't help. (also I'd prefer to be able to run the script just with ./script)

This started as a silly problem but now I'm genuinely curious to know how to solve it.

So, is there a solution to this problem or will I have to tolerate this little blinking cursor next to my animation?


Solution

  • Could you use trap?

    cleanup() {
        tput cnorm
    }
    
    trap cleanup EXIT
    
    tput civis
    while [ condition ]
    ...