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?

1
  • Might a map/associative array help you? Commented Aug 24, 2016 at 7:31

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

8 Comments

This does not work?!
@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; misc.flogisoft.com/bash/tip_colors_and_formatting#background1
On the mac its "\x1b[" and on linux its "\e"
But thats not the problem. In your sample i want AA to be "YELLOW"
@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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.