Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set terminal background color on linux terminal without using ncurses?

I've wrote a simple console program in C which uses ANSI escape codes to color its text.

Is there a way to temporarily set the background of the whole terminal to black and the default font color to light gray? Can this be reverted after the program ends?

I'd prefer to avoid using ncurses.

like image 452
user1887348 Avatar asked Dec 08 '12 07:12

user1887348


People also ask

How do I change the background color in Linux terminal?

“tput setaf” sets foreground color, “tput setab” sets background color, and “tput sgr0” resets all the settings to terminal default. There are 8 standard colors encoded in numbers from 0 to 7 (in order: black, red, green, yellow, blue, magenta, cyan, white).

How do I change font color in terminal?

Use Text preferences in Terminal to change the font, text, colour and cursor options for a Terminal window profile. To change these preferences in the Terminal app on your Mac, choose Terminal > Preferences, click Profiles, select a profile, then click Text.


2 Answers

Probably the simplest way to go is to set the background colour of your text with ANSI:

For instance using:

echo -e "\e[37m\e[41m"

will give you blue text on a red background (you can use this to test the effect in dramatic, easy to see colours).

Whereas

echo -e "\e[97m\e[40m"

will set the foreground to white and the background to black for the duration of your program.

If you find that you're getting a kind of ugly transition zone between your background colour and the terminal's just print a sufficient number of newlines to wipe the whole screen.

To use this in C, you'll obviously want printf instead of echo.

The wiki page on ANSI escape codes has additional information.

like image 160
Richard Avatar answered Oct 29 '22 04:10

Richard


How to do this depends on the terminal the user is using. It may be ANSI, it may be VT100, it might be a line printer. ncurses abstracts this horror for you. It uses a database of information about how to talk to different kinds of terminal (see the contents of $TERM to see which one you are currently using) normally stored in /lib/terminfo or /usr/share/terminfo.

Once you look in those files, you'll probably want to reconsider not using ncurses, unless you have specific requirements to avoid it (embedded system with not enough storage, etc.)

like image 33
rjek Avatar answered Oct 29 '22 03:10

rjek