Color text FUNCTION in BASH

Viewed 74

I am trying to make a function in bash that gets a parameter and based on that parameter it colors the text. Say colorText RED will color my text red. This is what I wrote so far but it says ./colorText: line 10: ${$1}dad: bad substitution

#!/bin/bash

RED="\033[31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
NC="\033[0m"

colorText () {
echo $1
echo -e "${$1}dad"
}

colorText $1

The last $1 is because I want to use the script file from my terminal.

4 Answers

So check if $1 is equal to RED, if it is, output $RED, repeat for every color. You can just switch on the color number.

case "$1" in
RED) n=31; ;;
GREEN) n=32; ;;
YELLOW) n=33; ;;
esac
echo -e "\033[${n}m"

A couple small tweaks to OP's current code:

colorText () {
    local -n color="${1}"           # define local variable as nameref
    echo -e "${color}dad${NC}"      # add ${NC} to turn off colorization
}

Taking for a test drive:

RED="\033[31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
NC="\033[0m"

colorText RED
colorText GREEN
colorText YELLOW
colorText BLUE                     # BLUE is undefined so there should be no color applied

This generates:

enter image description here

If you already created color variables then just use them as is, like this:

RED="\033[31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
NC="\033[0m"

colorText(){ echo -e "${1}dad"; }

colorText "$RED"

IMHO function is redundant here, just use echo -e or printf with color vars:

printf "${RED}dad${NC}"

ps. check out this

Related