Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Colored Output with a Variable

Tags:

variables

bash

I have the following function:

function pause #for prompted pause until ENTER
{


prompt="$3"
    echo -e -n "\E[36m$3" #color output text cyan
    echo -e -n '\E[0m' #ends colored output
    read -p "$*"  #read keys from user until ENTER.
    clear

}

pause "Press enter to continue..."

However, my function refuses to apply the cyan color to the string I pass into the function.

A similar question was asked here, but it seems that I'm doing everything correctly...

like image 506
derp Avatar asked May 05 '12 23:05

derp


2 Answers

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"
like image 114
Diego Schulz Avatar answered Oct 21 '22 15:10

Diego Schulz


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.
like image 22
marcelog Avatar answered Oct 21 '22 15:10

marcelog