Script Output Displays Multiple Text

Hello there,

I'm using a read-while loop to preserve the word Failed within a text file. For example, if the word Failed exist twice in a single text file, my STDOUT should re-direct to a new text file and display Failed twice.

My output is attached to this thread. I would like output to display only 5 lines not 20 lines. Based on my script, my echo command is only calling variable one time, not four times, according to script output.

Below is my script:

 #!/bin/bash

var="TestServer"
file="/usr/local/bin/Production/ESXiTestServer/cron.log"
go=$(grep 'Failed' "$file")

while read line; do
echo "from:me
subject:Failure on $var
message:${go}" >> mywindowsfile.txt

# Convert linux txt file to Windows txt format
awk 'sub("$", "\r")' mywindowsfile.txt > mywindows.txt

done < "$file"

I don't know exactly what is going on with output. Any suggestions on how to fix my output. My goal is to have output look like this:

from:TestServer@email.com
subject:Failure on TestServer
message: Physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SAS, 36 GB, Failed)
              Physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SAS, 36 GB, Failed)
```[/b]



You are using a while read loop that takes the input of the file. So it echoes the 5 output lines x the number of lines in the file, so there appear to be 4 lines in the file.

Just leave out the loop. It serves no purpose here..

1 Like

Thank you Scrutinizer for replying to my thread.

You are correct if I "Just leave out the loop".
script executes correctly, and its what am trying to achieve. But, if Failed doesn't exist, script will output a blank line and create a text file.

The reason why I'm using a while-loop is because if Failed isn't found, the script should exit and close program without creating a text file. So in other words, if Failed isn't found, script ends and exits. If Failed is found then re-direct output and send to text file.

How can I achieve this using a while-loop?

Don't use a while loop - use an if construct.

Thank you RudiC. I removed while statement and replaced with

if [ `$a | grep -c "Failed" -gt 0 ]

and script was able to copy standard output "Failed" on to a single text file when Failed was found on a log file.

Thanks again for all your help.