0

I have the following script which checks backup logs for errors and want it to print the error information that is standing in the line before the errorcode without also printing the errorcode. I tried this solution but I still get both lines.

#!/bin/bash
mytail=$(tail -n 13 bck.log)
mydate=$(date -dyesterday +%y%m%d)
bckerr=$(grep -B1 -i "backupexitcode:" bck.log | grep -v "backupexitcode:")

if [[ $mytail =~ $mydate ]]
then
        echo "Backup is up to date!"
        mytail=${mytail,,}
        if [[ "$mytail" == *failed* || "$mytail" != *backupexitcode:0* ]]
        then
                echo "There is an error in the last backup!"
                echo "$bckerr"
                        exit 1001
        else
                echo "No errors were found."
                        exit 0
        fi
else
        echo "Backup didn't run!"
                exit 1002
fi

The 2 lines that are involved seperated from the rest:

INFO         Older backups were deleted without error.
run_backup.sh(25863) 220228-200357: Instance:server:port Schema:"_instanceBackup" Finish: Timestamp:220228_200236 BackupExitCode:0

I've seen a few similar problems that were solved using sed or awk but none of those worked for me.

Icoryx
  • 96
  • 7

1 Answers1

0

To solve the problem you asked about you could replace this pipeline:

bckerr=$(grep -B1 -i "backupexitcode:" bck.log | grep -v "backupexitcode:")

with this single command (using GNU awk for IGNORECASE, easy to tweak for other awk versions too):

bckerr=$(awk -v IGNORECASE=1 '/backupexitcode/{print prev} {prev=$0}' bck.log)

In reality, though, most of your script should probably be replaced with a single call to awk such as:

$ cat tst.sh
#!/usr/bin/env bash

awk -v IGNORECASE=1 -v mydate="$(date -d yesterday +'%y%m%d')" '
BEGIN {
    msgs[0]    = "No errors were found."
    msgs[1001] = "There is an error in the last backup!"
    msgs[1002] = "Backup didn\047t run!"
    status = 1002
}
$0 ~ mydate {
    if ( /failed|backupexitcode:[1-9]/ ) {
        status = 1001
        msgs[status] = msgs[status] ORS prev
        exit
    }
    else {
        status = 0
    }
    prev = $0
}
END {
    print msgs[status] > "/dev/stderr"
    exit status
}
' 'bck.log'

but we'd need more information on the layout of bck.log, the expected output, and a few lines of sample input/output to really help you with that so ask a new question if you'd like more help.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185