Issue
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
Solution
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.
Answered By - Renaud Pacalet Answer Checked By - Gilberto Lyons (WPSolving Admin)