Skip to content

Instantly share code, notes, and snippets.

@arianacosta
Created July 15, 2017 19:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arianacosta/d6d1c521d231cc09ec5fe850ae2f5be1 to your computer and use it in GitHub Desktop.
Save arianacosta/d6d1c521d231cc09ec5fe850ae2f5be1 to your computer and use it in GitHub Desktop.
Print colored text in a bash script
#!/bin/bash
# prints colored text
print_style () {
if [ "$2" == "info" ] ; then
COLOR="96m";
elif [ "$2" == "success" ] ; then
COLOR="92m";
elif [ "$2" == "warning" ] ; then
COLOR="93m";
elif [ "$2" == "danger" ] ; then
COLOR="91m";
else #default color
COLOR="0m";
fi
STARTCOLOR="\e[$COLOR";
ENDCOLOR="\e[0m";
printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}
print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";
@MatsK
Copy link

MatsK commented Oct 10, 2021

I would include a newline ( \n ) to improve readability, ex.

print_style "This is a green text \n" "success";

print_style "This is a yellow text \n" "warning";

print_style "This is a light blue with a \t tab \n" "info";

print_style "This is a red text with a \n new line \n" "danger";

print_style "This has no color\n";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment