0

I have a script written and I want to include a function in the script, that silently logs the console output to a .txt file. The printf used in my shell scripts have colors for certain characters.

A sample:

# Color block

G="\033[32m"
N="\033[0m"
R="\033[31m"
Y="\033[33m"

# MCS Check

mcs=$(cat /home/admin/service-health.txt | grep -i mcs | cut -d ' ' -f 5 | tr . " ")

if [ "$mcs" == "up " ]
then
        printf "${Y}MCS${N} Service Status is\t\t |${G}UP${N}\n"
else
        printf "${Y}MCS${N} Service Status is\t\t |${R}DOWN${N}\n"
fi

Console output for this will display the color. This is not mandatory in the .txt logging.

I will then be emailing this .txt to an address using:

sendmail $vdp $eaddr  < /home/admin/health-check.txt

I used this block as I want to redirect the output within the script itself:

sudo touch /home/admin/health-check.txt
exec > >(tee -i /home/admin/health-check.txt)
exec 2>&1

But since this is a colored output, I keep getting this in my email:

[33mGSAN[0m Service Status is          |[32mUP[0m
[33mMCS[0m Service Status is           |[32mUP[0m
[33mTomcat[0m Service Status is        |[32mUP[0m
[33mScheduler[0m Service Status is     |[32mUP[0m
[33mMaintenance[0m Service Status is   |[32mUP[0m
VDP [33mAccess State[0m is             |[32mFULL[0m

Any thoughts about stripping colors during redirect? I do not want to use sed to find and replace as this looks tedious.

Thanks.

  • Welcome to Stack Overflow. Please read the [About] and [Ask] pages soon. What is your question? How to omit the colour encoding from the log file messages? Your script doesn't show the 'silent logging' mechanism, so we can't guess what options you have to fix it. You could test whether the standard output is an 'interactive device' (a terminal or a pseudo-tty) and decide not to include colouring unless it is, or unless commanded by an option to colour (analogous to `--color=always` options). You could strip the colour data out of the stream written to the log. No doubt there are others too. – Jonathan Leffler May 15 '17 at 21:45
  • Possible duplicate of [Removing colors from output](http://stackoverflow.com/questions/17998978/removing-colors-from-output) – Bor Laze May 15 '17 at 21:53
  • When you don't want to add and remove colors again, change your script into writing to 2 outputs.Use a function (like `colortee`) that will read your input and write double output. With some reserved words the `colortee` can replace the reserved words in escape codes for the colored stream. – Walter A May 15 '17 at 22:00

1 Answers1

0

You can direct the output using the > character. printf "mytext" > out.txt will print "mytext" to the file "out.txt"

Ryan Baker
  • 193
  • 7
  • This addresses the title of the question, but there isn't really a question in the body of the question yet. I think the OP knows how to do I/O redirection. – Jonathan Leffler May 15 '17 at 21:48