0

I am writing a bash script. I would like to print a colored string to the terminal via the echo command and have the color of the string change based on the background color of the terminal.

I currently am just printing the string in white like so: echo -e "$(tput setaf 7)my string here".

Is there a way to print the string in a different color if the terminal background color is also white? I would prefer not to set the background color myself to ensure that my string is visible.

Thanks in advance!

Alex Kleiman
  • 709
  • 5
  • 14
  • Is there any reason to not force a background color for the text? – Ignacio Vazquez-Abrams Sep 07 '14 at 01:57
  • Not any particularly compelling one. That's certainly a possibility, and the only reason I don't want to do that is for aesthetic reasons. Then again, it is a bash script, so if I do have to resort to that it wouldn't be the end of the world :) – Alex Kleiman Sep 07 '14 at 01:59
  • It depends on which terminal you're using. This post might help http://unix.stackexchange.com/questions/1755/change-the-ps1-color-based-on-the-background-color . – John B Sep 07 '14 at 02:36
  • 1
    See Also: [**Is there a way to determine a terminal's background color?**](http://stackoverflow.com/questions/2507337/is-there-a-way-to-determine-a-terminals-background-color) – David C. Rankin Sep 07 '14 at 07:44

1 Answers1

1

As far as I know, it's impossible to fetch the backgroud color of a terminal. Like John B said in the comments, it also depends on the terminal you are using.

If you want to force a specific background color you could use this command tput setab # where # is a number between 0 and 7. Then you could reset the background color to the original color using the parameter op like this : tput op

This link might also help (for the colors and more documentation on the color handling) : http://linux.about.com/library/cmd/blcmdl5_terminfo.htm

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
K-Jtan
  • 64
  • 1
  • 9
  • There is no reason to use `echo` in those commands. `tput` outputs raw control sequences and not escaped sequences such as `echo -e` interprets. – Etan Reisner Sep 07 '14 at 12:42