Skip to content

Instantly share code, notes, and snippets.

@yyogo
Last active August 15, 2023 08:16
Show Gist options
  • Save yyogo/96461abec24de6d9498465f00ea5fa83 to your computer and use it in GitHub Desktop.
Save yyogo/96461abec24de6d9498465f00ea5fa83 to your computer and use it in GitHub Desktop.
easy ANSI styling in bash
#!/bin/bash
style() {
if [ $# -eq 0 ]; then
echo 'usage: style [[<color name>|[color] <index>|rgb R G B|#<rgb hex>] [fg|bg]]'
echo ' | bold | dim | italic'
echo ' | blink [fast|slow]'
echo ' | underline | invert | hide | strike | reset]]...'
return 1
fi
printf "\x1b["
while [ $# -gt 0 ]; do
op=${1,,}; shift
case "$op" in
bold | bright) on=1; off=22 ;;
dim | faint) on=2; off=22 ;;
italic) on=3; off=23 ;;
underline) on=4; off=24 ;;
blink)
off=25
case $1 in
fast | rapid) on=6; shift ;;
slow) on=5; shift ;;
*) on=5 ;;
esac ;;
invert | reverse) on=7; off=27 ;;
hide | conceal) on=8; off=28 ;;
strike) on=9; off=29 ;;
reset | normal) printf 0; continue ;;
black) c=0;; red) c=1;; green) c=2;; yellow) c=3;;
blue) c=4;; purple) c=5;; cyan) c=6;; white) c=7;;
c256|color) c="8;5;$1"; shift ;;
rgb) r=$1; g=$2; b=$3; shift 3; c="8;2;$r;$g;$b" ;;
'#'*)
if [ ${#op} -eq 4 ]; then
r=$((0x${op:1:1}*16))
g=$((0x${op:2:1}*16))
b=$((0x${op:3:1}*16))
else
r=$((0x${op:1:2}))
g=$((0x${op:3:2}))
b=$((0x${op:5:2}))
fi
c="8;2;$r;$g;$b"
;;
*) continue ;;
esac
if [ -n "$on" ]; then
case "$1" in
on) printf %d "$on"; shift ;;
off) printf %d "$off"; shift ;;
*) printf %d "$on" ;;
esac
off=; on=
fi
if [ -n "$c" ]; then
case "$1" in
fg) c="3$c"; shift ;;
bg) c="4$c"; shift ;;
*) c="3$c" ;;
esac
printf %s "$c"
c=
fi
if [ "$#" -gt 0 ]; then printf ';'; fi
done
printf "m"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment