Home > Enterprise >  Bash script customize stdout and stderr in script
Bash script customize stdout and stderr in script

Time:09-27

I want to execute some scripts in install.sh, looks like:

#!/bin/bash

./script1.sh
./script2.sh
./script3.sh
...

It executes a bunch of scripts, so I want to distinguish stdout and stderr by color (green for stdout, red for stderr), and also where the outputs come from.

The output format I want is:

script1.sh: Hello                 # in green color (stdout)
script2.sh: Cannot read a file.   # in red color (stderr)

My goal is to print outputs in scripts in format of:

{script_name}: {green_if_stdout, red_if_stderr}

I don't want to edit every single command in all scripts.

Is there any way to override (or customize) all stdout and stderr outputs in the script?

#!/bin/bash

override_stdout_and_stderr

echo "Start"    # It also prints as green color

./script1.sh
./script2.sh
./script3.sh
...

restore_if_needed

CodePudding user response:

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'

One last idea on this, this only shows how a bash function behaves like a bash script and can have its stderr and stdout redirected.

#!/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"}' )
}

function something()
{
  ./script1.sh
  ./script1.sh
  ./script1.sh
}

colorize something
  • Related