Search code examples
linuxbashfunctionechovariable-assignment

Why does this work in this bash script's function?


I saw a function in a tutorial and I think it's pretty cool. It's for coloring text.

Function is defined like so:

function print_color(){

  case $1 in
    "green") COLOR='\033[0;32m' ;;
    "red") COLOR='\033[0;31m' ;;
    "*") COLOR='\033[0m' ;;
  esac

  echo -e "${COLOR} $2"

Then it's called like so:

# Install and configure firewalld
print_color "green" "Installing FirewallD.. "
apt search datadog

It'll then colorize the text "Installing FirewallD..".

So the function works only when you precede echoing $2 with ${COLOR}. My question is, how and why does this work this way? Why do I need to echo ${COLOR} so when I echo $2, it's colorized? If I remove the echoing of ${COLOR}, the colorization will not work. I want to know because I seek a deeper understand of BASH.

Thanks.

The script works. I want to know why it works the way it does.


Solution

  • They're called ANSI escape codes. You can use them like this (example code in python for simplicity's sake):

    red = "\033[0;31m"
    no_color = "\033[0m"
    print("Something with normal color " + red + "something with red " + no_color + "something with normal color")
    

    Which outputs "something with red" with red and everything else with the default color.