0

I want to create a function for colored output (just to learn bash a little better)

Here is what works

ESC_SEQ="\x1b["
# foreground red
FG_RED="${ESC_SEQ}31;"
# background yellow
BG_YELLOW="43;"
# style bold
FS_BOLD="1m"
# echo
echo -e "${FG_RED}${BG_YELLOW}${FS_BOLD}Hello World!"

No i try to build the function

function ext_echo() 
{
    // lets say $1 is RED, $2 is YELLOW, $3 is BOLD
    // so is need something like ...
    echo -e "${FG_$1}${BG_$2}${FS_$3}Hello World!"
}

How can i build my echo execution from that parameters?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
dknaack
  • 60,192
  • 27
  • 155
  • 202

2 Answers2

1
export ESC_SEQ="\e["
export YELLOW="43m"

function format_text() 
{
  BG="$ESC_SEQ$1"
  echo -e "${BG}Hello World!"
}

format_text $YELLOW

I don't know how and if it's possible without temporary variable. All examples I found use tmp variable to achieve it.

agilob
  • 6,082
  • 3
  • 33
  • 49
  • This does not work?! – dknaack Aug 24 '16 at 07:40
  • @dknaack You're coloring parameters seem to be wrong. I just showed you how to join strings to extract callable variable. Yellow is `\e[43m` not `43;` http://misc.flogisoft.com/bash/tip_colors_and_formatting#background1 – agilob Aug 24 '16 at 07:55
  • On the mac its "\x1b[" and on linux its "\e" – dknaack Aug 24 '16 at 08:05
  • But thats not the problem. In your sample i want AA to be "YELLOW" – dknaack Aug 24 '16 at 08:08
  • @dknaack I wasn't aware of it. I updated my example to work on Linux, it should be clear now how to convert it to OSX – agilob Aug 24 '16 at 08:14
  • Sorry but as i mentioned in my question is the value of a argument passed to a function. $COLOR="YELLOW" – dknaack Aug 24 '16 at 08:24
  • @dknaack Just replace variable YELLOW with function input? – agilob Aug 24 '16 at 08:25
  • ;) no that does not work. I have a "const" called BG_YELLOW which contains the value "\e[43m;" ... no i want a function where the user can pass in "YELLOW". No i build the variable and want to use it in echo -e – dknaack Aug 24 '16 at 08:31
1

The following script should be a good enough starting point:

#!/bin/bash


ext_echo()
{
  declare -A colors

  colors=(
    [red]="<red>"
    [blue]="<blue>"
  )

  for c in "$@"; do
    echo ${colors[$c]}
  done
}

ext_echo red blue

output

<red>
<blue>
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137