Skip to content

Instantly share code, notes, and snippets.

@lunatic-fox
Last active May 10, 2023 03:03
Show Gist options
  • Save lunatic-fox/f3bd4d1fd80ba9477a4f259f0df5880a to your computer and use it in GitHub Desktop.
Save lunatic-fox/f3bd4d1fd80ba9477a4f259f0df5880a to your computer and use it in GitHub Desktop.
Echo with colors on bash.
color() {
_0=$(echo $1 | sed -E "s/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})//")
if ((${#2} == 0))
then
echo $1
elif ((${#_0} == 0))
then
if ((${#1} == 7))
then
_0="$((16#${1:1:2}));$((16#${1:3:2}));$((16#${1:5:2}))"
else
_0="$((16#${1:1:1}${1:1:1}));$((16#${1:2:1}${1:2:1}));$((16#${1:3:1}${1:3:1}))"
fi
echo -e "\033[38;2;${_0}m$2\033[0m"
else echo $2; fi
}

Colors on bash console

Usage

# Allowed color patterns.
color "#0F0"    "Line in \"lime\" color."
color "#dc143c" "Line in \"crimson\" color."

# Not allowed.
color "#dc14" "Not allowed pattern."
color "Text only."

Terminal

  • ${\texttt{\color{lime}Line in "lime" color.}}$
  • ${\texttt{\color{crimson}Line in "crimson" color.}}$
  • ${\texttt{Not allowed pattern.}}$
  • ${\texttt{Text only.}}$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment