Search code examples
bashgreptail

Script to search for values in the log


I have an update program that either completes the update successfully or goes into error and needs to be restarted.

I am implementing the task itself on Ansible, but to control the process, a dynamic reading of the log using tail and grep is necessary, so I am implementing a script that will perform the task on its side and give the output success and failure.

This script does not work out the elif function, and shows the status only on success

#!/bin/bash

if tail -f -n3 /var/log/messages | grep -q "File update download fail"
then
  echo "Restart update"

elif tail -f -n3 /var/log/messages | grep -q "Update success"
then
  echo "Update success"

fi

exit 1

Solution

  • tail -f generally does not exit on its own, and grep -q will only exit if it reaches end-of-file or matches a pattern. Combining the two commands results in a statement that is unlikely to ever exit until it succeeds, meaning you will probably never reach your elif condition.

    What you need is a loop that processes each line of output and allows every condition to be checked against each line.

    #!/bin/bash
    tail -f -n3 /var/log/messages | while read -r line ; do
      case "${line}" in
        *"File update download fail"*)  echo "Restart update" ; exit 1 ;;
        *"Update success"*) echo "Update success" ; exit 0 ;;
      esac
    done