You could use a second condition that uses some variable (or file) as flag (or counter).
For example to use a file as flag you could modify your script in this way:
#!/bin/bash
FLAG_FILE="/tmp/flag_file_my_error_email_script"
if grep -iq 'error' "/path/to/log" && [ ! -f "${FLAG_FILE}" ]; then
echo "error found" | mailx -s "error alert" email-id
touch "$FLAG_FILE"
fi
The command touch "$FLAG_FILE"
will create the file /tmp/flag_file_my_error_email_script
that is used as an argument in the second condition [ ! -f "${FLAG_FILE}" ]
. Read about Bash Conditional Expressions.
If you want to send/receive a certain number of emails and then to suppress the script's function, you could add third condition, where the content of the $FLAG_FILE
will be used as counter:
#!/bin/bash
FLAG_FILE="/tmp/flag_file_my_error_email_script"
if grep -iq 'error' "/path/to/log" && [ ! -f "${FLAG_FILE}" ] || (( $(cat "$FLAG_FILE") < 2 )); then
echo "error found" | mailx -s "error alert" email-id
touch "$FLAG_FILE"
NEW_VALUE=$(( $(cat "$FLAG_FILE") + 1)) && echo "$NEW_VALUE" > "$FLAG_FILE"
fi
Note that &&
have а meaning of if the previous condition returns true and ||
means if the previous condition returns false.
If you want to restore the "normal" work of the script you should remove the $FLAG_FILE
. This file will be automatically deleted on system reboot. If you want to change that behaviour, choice a directory different from /temp
where the user that executes the script has write permissions.