Cancel

Fatal, Warning, Success, and Info color codes in Bash

Make your bash script messages colorful. I am going to use the xterm-256 color code because it is supported by pretty much all terminals.

  • Foreground Formula Code: 38
  • Background Formula Code: 48
  • Style Formula Range: from 0 to 5
  • xterm Colors Range: from 1 to 256

Let’s create a function and add our formula and values accordingly to print colorful messages on user’s screen.

1
2
3
4
beautify() {
  reset_color="\033[0m"
  echo -e "\033[$1;5;$2m$3$reset_color"
}
  • \033 means escape code, which will let your print or echo command to return colorful messages.
  • [ must be there don’t know why.
  • $1 means Foreground/Background color code as mentioned above.
  • ; semicolon is for separate your above 3 statements.
  • 5 means Style Range as mentioned above.
  • $2 means Color Range as mentioned above.
  • m must be there don’t know why.
  • $3 means you can add any kind of message here.
  • $reset_color your terminal will be back on normal color mode.

Foreground colorful messages…

1
2
3
4
beautify 38 9 "fatal: message can be written here"
beautify 38 10 "warning: message can be written here"
beautify 38 11 "success: message can be written here"
beautify 38 15 "info: message can be written here"

Background colorful messages…

1
2
3
4
beautify 48 9 "fatal: message can be written here"
beautify 48 10 "warning: message can be written here"
beautify 48 11 "success: message can be written here"
beautify 48 15 "info: message can be written here"

You can also combine your background and foreground together.

Here we are just removing 5; from the folmula, rest eveything will remain same.

1
2
3
4
beautify_combine() {
  reset_color="\033[0m"
  echo -e "\033[$1;$2m$3$reset_color"
}

Background + Foreground colorful messages…

1
2
3
4
beautify_combine '38;5;0' '48;5;9' "fatal: message can be written here"
beautify_combine '38;5;0' '48;5;10' "warning: message can be written here"
beautify_combine '38;5;0' '48;5;11' "success: message can be written here"
beautify_combine '38;5;0' '48;5;15' "info: message can be written here"

You can also Blink your test like animation.

1
beautify_combine '5;38;5;0' '48;5;9' "fatal: message can be written here"

You can run 4 loops as well to print different colors at once. You have a maximum 256 range limit.

1
2
3
for x in {1..50}; do
  beautify 38 $x "message can be written here"
done