Here are a couple of things you can do:
Editors + Code
A lot of editors have syntax highlighting support. vim
and emacs
have it on by default. You can also enable it under nano
.
You can also syntax highlight code on the terminal by using Pygments as a command-line tool.
grep
grep --color=auto
highlights all matches. You can also use export GREP_OPTIONS='--color=auto'
to make it persistent without an alias. If you use --color=always
, it'll use colour even when piping, which confuses things.
ls
ls --color=always
Colors specified by:
export LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33'
(hint: dircolors
can be helpful)
PS1
You can set your PS1 (shell prompt) to use colours. For example:
PS1='\e[33;1m\u@\h: \e[31m\W\e[0m\$ '
Will produce a PS1 like:
[yellow]lucas@ubuntu: [red]~[normal]$
You can get really creative with this. As an idea:
PS1='\e[s\e[0;0H\e[1;33m\h \t\n\e[1;32mThis is my computer\e[u[\u@\h: \w]\$ '
Puts a bar at the top of your terminal with some random info. (For best results, also use alias clear="echo -e '\e[2J\n\n'"
.)
Getting Rid of Escape Sequences
If something is stuck outputting colour when you don't want it to, I use this sed
line to strip the escape sequences:
sed "s/\[^[[0-9;]*[a-zA-Z]//gi"
If you want a more authentic experience, you can also get rid of lines starting with \e[8m
, which instructs the terminal to hide the text. (Not widely supported.)
sed "s/^\[^[8m.*$//gi"
Also note that those ^[s should be actual, literal ^[s. You can type them by pressing ^V^[ in bash, that is Ctrl + V, Ctrl + [.
\xNN
is an escape sequence in GNU sed, but it is not standard, and in particular it is not available on Solaris.
You can include a literal escape character in your script, but that would make it hard to read and edit.
You can use printf
to generate an escape character. It understands octal escapes, not hexadecimal.
esc=$(printf '\033')
echo "test" | sed "s,.*,${esc}[31m&${esc}[0m,"
You can call tput
to generate the replacement text in the call to sed. This command looks up escape sequences in the terminfo database. In theory, using tput
makes your script more portable, but in practice you're unlikely to encounter a terminal that doesn't use ANSI escape codes.
echo "test" | sed "s,.*,$(tput setaf 1)&$(tput sgr0),"
Best Answer
Most programs that produce color will, by default, only produce it when the output is to a terminal, not a pipe or file. Generally, this is a good thing. Often, however, there is an override switch. For example, for
ls
, one can use--color=always
and, as a result, color can be saved in shell variables. For example:grep
also supports the--colors=always
option.For git, the corresponding option is its
color.ui
configuration setting: