Bash-- trap CTRL+C reset terminal properties and end infinite while loop

705 views Asked by At

So I have this infinite loop that changes terminal properties such as foreground/background color.

Specifications: When CTRL+C is pressed, before exiting the loop/script it should reset the terminal to original properties.

Now I think I need to trap CTRL+C and somehow use setterm reset to reset the terminal, but just can't seem to integrate to the script.

When I trap the CTRL+C, outside the while loop it doesn't reset the terminal. It doesn't work inside the infinite loop also.

Upon exit the terminal properties stay changed,

example:

    #!/bin/bash
    while true;
    do
    tput civis 
    tput bold 
    tput setb 2 
    tput setf 4  
    tput bold 
    tput 10 40; echo "hello"
    tput 11 40; echo "there"
    done

How do I trap CTRL+C, reset terminal, and exit?

1

There are 1 answers

0
Bruce Strafford On

Never mind.. using trap 'reset; exit' SIGINT inside the loop solves this problem.