(seperti yang dibahas dalam komentar, gunakantput
sebaliknya jika Anda memilikinya)
Menggunakan bourne shell dan echo
(built-in) perintah yang memahami opsi ANSI melarikan diri \e
dengan -e
:
black() { IFS= ; while read -r line; do echo -e '\e[30m'$line'\e[0m'; done; }
red() { IFS= ; while read -r line; do echo -e '\e[31m'$line'\e[0m'; done; }
green() { IFS= ; while read -r line; do echo -e '\e[32m'$line'\e[0m'; done; }
yellow() { IFS= ; while read -r line; do echo -e '\e[33m'$line'\e[0m'; done; }
blue() { IFS= ; while read -r line; do echo -e '\e[34m'$line'\e[0m'; done; }
purple() { IFS= ; while read -r line; do echo -e '\e[35m'$line'\e[0m'; done; }
cyan() { IFS= ; while read -r line; do echo -e '\e[36m'$line'\e[0m'; done; }
white() { IFS= ; while read -r line; do echo -e '\e[37m'$line'\e[0m'; done; }
echo ' foo\n bar' | red
atau, skrip shell yang lebih umum (katakanlah, /usr/local/bin/colorize
):
#!/bin/sh
usage() {
echo 'usage:' >&2
echo ' some-command | colorize {black, red, green, yellow, blue, purple, cyan, white}' >&2
exit 1
}
[ -z "$1" ] && usage
case $1 in
black) color='\e[30m' ;;
red) color='\e[31m' ;;
green) color='\e[32m' ;;
yellow) color='\e[33m' ;;
blue) color='\e[34m' ;;
purple) color='\e[35m' ;;
cyan) color='\e[36m' ;;
white) color='\e[36m' ;;
*) usage ;;
esac
IFS=
while read -r line; do
echo -e $color$line'\e[0m'
done
IFS=
diperlukan untuk mencegah pemotongan spasi putih (lihat POSIX untuk detailnya).