13

I was trying to remember how I could pre-define colors inside of .bashrc file so they could be called on when I do ${RED} for example.

I can't remember if this was the right way of doing it, but it was something like this if I can remember;

NC="\033[0;0;0m"      # no color or formatting
RED="\033[1;49;91m"   # color red
BLU="\033[1;49;94m"   # color blue
GRN="\033[1;49;32m"   # color green

another I recall, was using function so it could be use at any time anywhere. I did have a file showing me how to do this but I lost this file which showed how to do it, and I can't remember how it goes.

3 Answers 3

12

You can define a function in your ~/.bashrc as follows

showred(){
    export RED='\033[1;49;91m'
    export NC='\033[0;0;0m'
    echo -e $RED"$@"$NC
}

Source ~/.bashrc as . ~/.bashrc or open a new terminal and try.

enter image description here

Also you can write in colours while writing something on terminal using echo or printf as following,

enter image description here

1
  • This seems like a friendlier and cleaner way of doing this.
    – user94959
    Mar 1, 2015 at 15:03
4
declare -r RED='\033[0;31m'
declare -r GREEN='\033[0;32m'
declare -r NC='\033[0m'
3

You may have seen the $'...' syntax, which causes the shell to interpret backslash sequences:

NC=$'\e[0m'       # no color or formatting
RED=$'\e[1;31m'   # color red
GRN=$'\e[1;32m'   # color green
BLU=$'\e[1;34m'   # color blue

Another way to do this, using tput:

NC=$(tput sgr0)                  # no color or formatting
RED=$(tput bold; tput setaf 1)   # color red
GRN=$(tput bold; tput setaf 2)   # color green
BLU=$(tput bold; tput setaf 4)   # color blue

You can combine these with the wrapper functions in souravc's answer; you won't need -e.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy