If you want a quick easy way to add some colors to your own shell scripts:
export STDOUT_COLOR_START='[34m'
export STDOUT_COLOR_STOP='[0m'
export STDERR_COLOR_START='[31m'
export STDERR_COLOR_STOP='[0m'
In your shell script: print_stdout() {
printf %s%s%s\\n "${STDOUT_COLOR_START:-}" "$*" "${STDOUT_COLOR_STOP:-}"
}
print_stderr() {
>&2 printf %s%s%s\\n "${STDERR_COLOR_START:-}" "$*" "${STDERR_COLOR_STOP:-}"
}
Source: https://github.com/sixarm/unix-shell-script-kitThe source also has functions for nocolor, and detecting a dumb terminal setup that doesn't use colors, etc.
1. That script's color check doesn't check that the output is a terminal. Also test
2. Don't hardcode escape sequences. Use (e.g.)Yes good points both, thank you. The source code link has more explanation about color choices and my preference of POSIX compatibility. You can also see the color function that checks NO_COLOR, CLICOLOR_FORCE, TERM = "dumb", -t 1, etc.
For color operands, I use raw escape codes because I aim for POSIX compatibility. If I'm working on something that needs more capabilities then I switch to a more powerful programming language e.g. python, rust, etc.
As far as I understand, POSIX tput defines some terminal operands (clear, init, reset, etc.) but not color operands (setaf, setab, sgr0, etc.).
If you're writing a zsh script and not worried about portability, you can also use the prompt expansion colors with "print".
And then to use itHere's something also useful that's portable
Nice. I put this in my .zshrc.
That seems needlessly cumbersome, why not
Like why are you exporting? Do you really need those in your environment?And those print statements aren't going to work by default.
Good questions.
For shell syntax, I aim for POSIX because for anything more advanced I switch from shell to a more powerful programming language.
Currently POSIX doesn't have the 'declare' statement, nor the '\e' syntax consistently, nor the 'echo -e' syntax consistently.
As for exporting, I do it because I have many quick scripts that I run often, and I prefer to switch the colors in one place such as in the evening from light mode to dark mode.
When you say the print statements aren't going to work by default, can you say more about this? Anything you can explain or point me to about this will be a big help. Thanks!
What is the purpose of making everything the same color?
stdout and stderr get different colors.