1

I wrote a script that greps for a word in log and sends email if that word (error) is found, the script runs every hour and if that word (error) is found it will be there one day and next day the log starts again and error may not be found.

So script running every hour does send me every hour same email if that error is found, how can i stop sending after 2 times or only one time.

if grep 'error' "/path to log"; then
    echo "error found" | mailx -s "error alert" email-id
fi
0

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.