Home > front end >  How to find errors in a file using for loop
How to find errors in a file using for loop

Time:11-27

How I can find errors (Error1, Error2 , Error 3) from a file using for loop.

A file contains three types of errors (strings) from 4 different machines. Any machine can have any number of errors. whiptail is used to create a pop-up window whenver an error is found.

#!/bin/sh

 
if grep -R "Error1 in Machine 1" /home/new/Report.txt
then
echo "Error1 found in Machine 1"
whiptail --title "Report Error" --msgbox "Error 1 in Machine 1" 8 78
else
echo "No Error found"
fi


if grep -R "Error2 in Machine 1" /home/new/Report.txt
then
echo "Error2 found in Machine 1"
whiptail --title "Report Error" --msgbox "Error 2 in Machine 1" 8 78
else
echo "No Error found"
fi


if grep -R "Error2 in Machine 2" /home/new/Report.txt
then
echo "Error2 found in Machine 2"
whiptail --title "Report Error" --msgbox "Error 2 in Machine 2" 8 78
else
echo "No Error found"
fi


if grep -R "Error3 in Machine 3" /home/new/Report.txt
then
echo "Error3 found in Machine 3"
whiptail --title "Report Error" --msgbox "Error 3 in Machine 3" 8 78
else
echo "No Error found"
fi

CodePudding user response:

Bash syntax like {1..3} is often great for this

for index in {1..3}; do
    [[ grep -R -q "Error${index} in Machine ${index}" /home/new/Report.txt ]] {
        echo "Error2 found in Machine ${index}"
        whiptail --title "Report Error" --msgbox "Error ${index} in Machine ${index}" 8 78
    } || {
        echo "No Error found for Machine ${index}"
    }
done

CodePudding user response:

If you have 3 errors and 4 machines you can use nested loops to handle all 12 combinations:

for ((e = 1; e <= 3; e  )); do
  for ((m = 1; m <= 4; m  )); do
    message="Error$e in Machine $m"
    if grep -qF "$message" /home/new/Report.txt; then
      echo "$message"
      whiptail --title "Report Error" --msgbox "$message" 8 78
    else
      echo "No Error found"
    fi
  done
done

The grep options q (quiet) and F are used to not print anything and to interpret the pattern as a fixed string, not a regular expression.

CodePudding user response:

Pass grep(1) one time and save the output, then do the rest.

#!/usr/bin/env bash

mapfile -t error_message < <(grep 'Error[[:digit:]] in Machine [[:digit:]]' /home/new/Report.txt)

((${#error_message[*]})) || { printf >&2 'No error message found\n'; exit; }

for message in "${error_message[@]}"; do
  printf '%s\n' "$message"
  whiptail --title "Report Error" --msgbox "$message" 8 78
done

CodePudding user response:

#!/bin/bash

grep 'Error[1-3] in Machine [1-4]' /home/new/Report.txt |
while IFS= read -r errmsg
do
        whiptail --title "Report Error" --msgbox "$errmsg" 8 78
done

The script doesn't put the "No error found" message (no news is good news), but otherwise should work.

  • Related