Color Linux command output [duplicate] Color Linux command output [duplicate] bash bash

Color Linux command output [duplicate]


You can use escape sequences to change the font color of any output to the bash shell. Here are some of the color codes you'll need:

BLACK="\033[30m"RED="\033[31m"GREEN="\033[32m"YELLOW="\033[33m"BLUE="\033[34m"PINK="\033[35m"CYAN="\033[36m"WHITE="\033[37m"NORMAL="\033[0;39m"

Once these are defined, you can use them in normal echo commands. For instance:

echo -e $GREEN this text is green $NORMAL and this is normal

Note that the -e is not always necessary, but on some OSs (incl. osx) is required for to enable escape sequences.

Given these definitions you can build scripts and pipes to color the output from other commands. Here is a complete example I use to color the output from svn up:

#!/bin/bashBLACK="\033[30m"RED="\033[31m"GREEN="\033[32m"YELLOW="\033[33m"BLUE="\033[34m"PINK="\033[35m"CYAN="\033[36m"WHITE="\033[37m"NORMAL="\033[0;39m"TMPFILE=.cvsup.tmpsvn up > $TMPFILEsvn status >> $TMPFILEprintf $YELLOWgrep -e ^"\? " -e ^"I " $TMPFILEprintf $GREENgrep -e ^"R " -e ^"U " -e ^"G " $TMPFILEprintf $BLUEgrep -e ^"M " -e ^"E " $TMPFILEprintf $REDgrep -e ^"C " -e ^"! " -e ^"X " -e ^"~ " $TMPFILEprintf $PINKgrep ^"R " $TMPFILEprintf $PINKgrep ^"D " $TMPFILEprintf $CYANgrep ^"A " $TMPFILEprintf $NORMALrm $TMPFILE

You can also look at tput.


norm="$(printf '\033[0m')" #returns to "normal"bold="$(printf '\033[0;1m')" #set boldred="$(printf '\033[0;31m')" #set redboldred="$(printf '\033[0;1;31m')" #set bold, and set red.somecommand | sed -e "s/someregexp/${boldred}&${norm}/g"  # will color any occurence of someregexp in Bold redprintf "%s" "$red" ; locate something ; printf "%s" "$norm"  # will color output of locate something in red   #I (ab)use printf "%s" "something", as it's more portable than echo,and easy to modify

There are many other ways (create a function/script that can colorize a regexp, for example, and then : somecommand | colorize -c green 'foo.*bar' 'other' )


As suggested by Jonathan Leffler, comment posted as an anwser:

grep --color will provide colour