You asked how to color all of stdout and stderr and prefix all lines with the script name.
In the answer below used redirection to send stdout to one process and stderr to another process. Credit to how to redirect stderr.
Using awk to prefix the incoming output with the needed color, red or green, then printing each line of input, and clearing the color setting upon finishing the print.
#!/bin/bash
function colorize()
{
"$@" 2> >( awk '{ printf "'$1':""\033[0;31m" $0 "\033[0m\n"}' ) \
1> >( awk '{ printf "'$1':""\033[0;32m" $0 "\033[0m\n"}' )
}
colorize ./script1.sh
#!/bin/sh
# script1.sh
echo "Hello GREEN"
>&2 echo "Hello RED"
Expect output similar to this command.
printf 'script1.sh:\033[0;32mHello GREEN\033[0m\nscript1.sh:\033[0;31mHello RED\033[0m\n'
Using read instead of awk:
#!/bin/bash
function greenchar()
{
while read ln ; do
printf "$1:\033[0;32m${ln}\033[0;0m\n" >&1
done
}
function redchar()
{
while read ln ; do
printf "$1:\033[0;31m${ln}\033[0;0m\n" >&2
done
}
function colorize()
{
$* 2> >( redchar $1 ) 1> >( greenchar $1 )
}
colorize ./script2.sh
#!/bin/bash
# script2.sh
echo "Hello GREEN"
>&2 echo "Hello RED"
>&1 echo "YES OR NO?"
select yn in "Yes" "No"; do
case $yn in
Yes) echo "YOU PICKED YES" ; break;;
No) echo "YOU PICKED NO" ; break;;
esac
done
Example output, the output is similar to output of these commands.
RED="\033[0;31m"
GRN="\033[0;32m"
NC="\033[0;0m"
printf "./script1.sh:${GRN}Hello GREEN${NC}\n"
printf "./script1.sh:${GRN}YES OR NO?${NC}\n"
printf "./script1.sh:${RED}Hello RED${NC}\n"
printf "./script1.sh:${RED}1) Yes${NC}\n"
printf "./script1.sh:${RED}2) No${NC}\n"
printf "${NC}1${NC}\n"
printf "./script1.sh:${GRN}YOU PICKED YES${NC}\n"