Search code examples
linuxbashcolors

Color text FUNCTION in BASH


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.


Solution

  • Try this:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    declare -A c
    c["RED"]='31'
    c["GREEN"]='32'
    c["YELLOW"]='33'
    c["BLACK"]='0'
    
    colorText () {
        printf '%s\n' "$1"
        printf '\e[%sm%s\e[0m\n' "${c[$1]}" 'dad'
    }
    
    colorText "$1"
    

    See also:

    1. tput-setaf-color-table-how-to-determine-color-codes
    2. using-awk-to-color-the-output-in-bash.