How to easily add colored text output in bash scripts
Here is small snippet that can give your shell scripts some nice output: colortext.sh As with the debug.sh script, just download it to the same directory as your own script and add it with
1 | . colortext.sh |
It contains one simple function called text with the syntax text “text to be output”. Color can be red, green, yellow, blue or grey. The function does not automatically add a linebreak to the putput, so pop a \n in there if you need it. I prefer using it together with printf for clean and easy color output.
Here are some examples of how the function can be used, and below the corresponding output:
1 2 3 4 5 6 7 8 9 10 11 | . colortext.sh echo "normal text" text blue "blue text, " text yellow "yellow text\n" # Using it together with echo echo -n "Status of script: [";text red "ERROR";echo "]" # more elegant usage with printf printf "Status of script: [%s]\n" $(text green "OK") |
Output:
normal text
blue text, yellow text
Status of script: [ERROR]
Status of script: [OK]