0

In a Bash script I need to print out some text in colors.

However, I don't want to specify fixed colors. I want to use the ones that are specified by the terminal(/-emulator).

How can I programmatically access them? Usually these must be a set of 16 colors. Two of them must be labeled background and foreground.

There should be a way to do so, since other programs as fish, Emacs, etc. also appear in the colors specified in the terminal emulator.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anton Harald
  • 5,772
  • 4
  • 27
  • 61
  • 1
    See http://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux – Guido Apr 01 '16 at 22:41
  • 1
    You are probably thinking of `tput`. Here's a good [documentation](http://linuxcommand.org/lc3_adv_tput.php) you can start with. – alvits Apr 01 '16 at 22:48
  • thx! this is already a great help. I could capture the numbered colors via tput (from 0-15) now, but what about the two others: "foreground" and "background", they are also specified in the theme of my terminal emulator. – Anton Harald Apr 01 '16 at 22:54
  • `setaf` and `setab` are used to set the foreground and background colors. – Barmar Apr 01 '16 at 22:57
  • oh, I used (tput setaf n) for setting the foreground color. But I'm looking for the specified color for background and foreground. – Anton Harald Apr 01 '16 at 22:59
  • for instance: I'd like to generate a color like so: read out the background-color, then change this color a bit towards grey. If the background is a dark color like black, the color will be slightly brighter. If the background color is a light color like white, the color will be slightly darker... – Anton Harald Apr 01 '16 at 23:07
  • All colors are terminal-specific. ANSI may say, for example, that `\e[32m` instructs the terminal to use green, but it's ultimately up to the terminal emulator to decide what "green" means. You can only find out the "real" color being used if the specific terminal emulator provides a way to make that query. – chepner Apr 01 '16 at 23:12
  • Unfortunately `tput` is not written to read the current color of the terminal, hence the name `tput`. It can only query for the capability. You'll probably get lucky with a more advanced ncurse based programming. Try writing in c or c++ with ncurse. – alvits Apr 01 '16 at 23:19

1 Answers1

0

Make a color profile file profile like below

export RED='\033[0;31m'
export GREEN='\033[1;32m'
export WHITE='\033[1;37m'

Include the above file in your script and change the color using printf as needed.

#!/bin/bash
source $( dirname $0 )/profile

#Switching to RED

printf "${RED}"
ls

#Switching to GREEN

printf "${GREEN}"
echo "Current working directory is "`pwd`
echo "/etc/passwd contents"
cat /etc/passwd

#Switching back to white

printf "${WHITE}"

echo "Some white stuff"

The colors persist till we change them.

sjsam
  • 21,411
  • 5
  • 55
  • 102