| ▲ | jph 7 hours ago |
| 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. |
|
| ▲ | godelski 4 hours ago | parent | next [-] |
| That seems needlessly cumbersome, why not declare STDOUT_COLOR='\e[34m'
declare STDERR_COLOR='\e[31m'
declare COLOR_STOP='\e[0m'
print_stdout() {
echo -e "${STDOUT_COLOR}${*}${COLOR_STOP}" &> /dev/stdout
}
print_stderrr() {
echo -e "${STDERR_COLOR}${*}${COLOR_STOP}" &> /dev/stderr
}
Like why are you exporting? Do you really need those in your environment?And those print statements aren't going to work by default. |
|
| ▲ | kps 6 hours ago | parent | prev | next [-] |
| 1. That script's color check doesn't check that the output is a terminal. Also test tty -s
2. Don't hardcode escape sequences. Use (e.g.) export STDOUT_COLOR_START="`tput setaf 4`".
|
|
| ▲ | wpm 6 hours ago | parent | prev | next [-] |
| If you're writing a zsh script and not worried about portability, you can also use the prompt expansion colors with "print". print_color () {
print -P "%F{$1}$2%f"
}
And then to use it print_color "green" "This is printed in green"
|
| |
| ▲ | godelski 4 hours ago | parent | next [-] | | Here's something also useful that's portable declare GRN='\e[1;32m'
declare RED='\e[1;31m'
declare YLW='\e[1;33m'
declare CYN='\e[1;36m'
write_log() {
echo -e "[$( date +'%c' )] : ${1}\e[0m" | tee -a ${logfile}
}
write_log "${RED}I'm an ERROR"
| |
| ▲ | leephillips 5 hours ago | parent | prev [-] | | Nice. I put this in my .zshrc. |
|
|
| ▲ | direwolf20 7 hours ago | parent | prev [-] |
| What is the purpose of making everything the same color? |
| |