Bash: Colored Output with a Variable

Try this:

RESTORE='\033[0m'

RED='\033[00;31m'
GREEN='\033[00;32m'
YELLOW='\033[00;33m'
BLUE='\033[00;34m'
PURPLE='\033[00;35m'
CYAN='\033[00;36m'
LIGHTGRAY='\033[00;37m'

LRED='\033[01;31m'
LGREEN='\033[01;32m'
LYELLOW='\033[01;33m'
LBLUE='\033[01;34m'
LPURPLE='\033[01;35m'
LCYAN='\033[01;36m'
WHITE='\033[01;37m'

function test_colors(){

  echo -e "${GREEN}Hello ${CYAN}THERE${RESTORE} Restored here ${LCYAN}HELLO again ${RED} Red socks aren't sexy ${BLUE} neither are blue ${RESTORE} "

}

function pause(){
  echo -en "${CYAN}"
  read -p "[Paused]  $*" FOO_discarded
  echo -en "${RESTORE}"
}


test_colors
pause "Hit any key to continue"

And there's more fun with backgrounds

echo -e "\033[01;41;35mTRY THIS\033[0m"
echo -e "\033[02;44;35mAND THIS\033[0m"
echo -e "\033[03;42;31mAND THIS\033[0m"
echo -e "\033[04;44;33mAND THIS\033[0m"
echo -e "\033[05;44;33mAND THIS\033[0m"

To save others time:

https://gist.github.com/elucify/c7ccfee9f13b42f11f81

No need to $(echo -ne) all over the place, because the variables defined in the gist above already contain the control characters. The leading/trailing \001 & \002 tell bash that the control characters shouldn't take up space, otherwise using these in a $PS1 will confuse readline.

RESTORE=$(echo -en '\001\033[0m\002')
RED=$(echo -en '\001\033[00;31m\002')
GREEN=$(echo -en '\001\033[00;32m\002')
YELLOW=$(echo -en '\001\033[00;33m\002')
BLUE=$(echo -en '\001\033[00;34m\002')
MAGENTA=$(echo -en '\001\033[00;35m\002')
PURPLE=$(echo -en '\001\033[00;35m\002')
CYAN=$(echo -en '\001\033[00;36m\002')
LIGHTGRAY=$(echo -en '\001\033[00;37m\002')
LRED=$(echo -en '\001\033[01;31m\002')
LGREEN=$(echo -en '\001\033[01;32m\002')
LYELLOW=$(echo -en '\001\033[01;33m\002')
LBLUE=$(echo -en '\001\033[01;34m\002')
LMAGENTA=$(echo -en '\001\033[01;35m\002')
LPURPLE=$(echo -en '\001\033[01;35m\002')
LCYAN=$(echo -en '\001\033[01;36m\002')
WHITE=$(echo -en '\001\033[01;37m\002')

# Test
echo ${RED}RED${GREEN}GREEN${YELLOW}YELLOW${BLUE}BLUE${PURPLE}PURPLE${CYAN}CYAN${WHITE}WHITE${RESTORE} 

I've slightly changed your code:

#!/bin/bash

function pause() {
    prompt="$1"
    echo -e -n "\033[1;36m$prompt"
    echo -e -n '\033[0m'
    read
    clear
}

pause "Press enter to continue..."

What I've changed:

  1. You were initializing prompt to $3, when the correct argument was $1
  2. The ANSI sequence was incorrect. See: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
  3. The call to read was incorrect, you were passing several arguments do to the use of $*. In this particular case you are discarding the input, so it's not even necessary to save the result of read. I suggest you to read the manpage: http://linux.die.net/man/1/bash to see how to exactly use read. If you pass in several arguments, those arguments will be mapped to variable names that will contain the different fields inputted in the line.

Tags:

Variables

Bash