In Linux, in order to display text in different colors on the terminal, you have to use the tput command. It has the ability to set the background and foreground color of text. You have to use the following command options:
- tput setaf
: Set foreground color. - tput setab
: Set background color.
However the number of colors available is limited. The command tput colors shows the number of colors available. On my system, it is 256.
Below is a Bash function example that will print the number in green if it is position and red if it is negative.
#!/bin/bash set -e function F_PRINT_COLOR_NUMBERS() { local LABEL=$1 local VALUE=$2 local COLOR_CODE="" if [ "${VALUE}" -lt 0 ]; then COLOR_CODE=$(tput setaf 1) # red color. else COLOR_CODE=$(tput setaf 2) # green color. fi local RESET_COLOR=$(tput sgr0) printf "%22s: ${COLOR_CODE}%'6d${RESET_COLOR}\n" "${LABEL}" "${VALUE}" } F_PRINT_COLOR_NUMBERS "Oil" 7921 F_PRINT_COLOR_NUMBERS "Gasoline" -369
Output
Github
- https://github.com/xuanngo2001/Scripts/blob/master/bash/print-number-with-color.sh