Trying to understand terminal behavior when it comes to reset background color on a Unix-like OS (Mac, Linux).
Consider a bash script
#!/usr/bin/env bash
printf "\033[46m"
printf "On Cyan\n"
printf "\033[0m"
printf "Back to Normal\n"
When I initially run this script, everything is as expected. However, if I repeat it for several times, the printing result changes. Following "Back to Normal" is a line on cyan background color.
The screenshot (Terminal, Mac OS Mojave):
Questions:
- Why is this? Can anyone explain this behavior?
- If I have changed background color and have printed out a line (ending with newline), what can I do to properly reset the background and to avoid this unwanted trailing background color?
For your information, I have tested this behavior on Mac OS Mojave Terminal, and on Ubuntu 18.04 Terminal. And I have tested using an equivalent Python 3 script. Results are consistent. I also tried using fflush(stdout) in C/C++ but in vain.
P.S. This question stems from a C++ program to be run on Mac or Linux. I thought it is irrelevant to the language itself, so I simplified it down to a bash script. If possible, please suggest a solution that can be done in C/C++.
