1

I try to calculate time differences between two log, but when there is no log in logfile, unix takes own birthdate 1970. My script is below. I want to exit from script if there is no log in logfile.

#!/bin/bash
a=`tail -n 1 /var/log/nginx/error.log | awk -F" " '{print $1" "$2}' | cut -c12-20`
f=`date '+%Y-%m-%d %H:%M:%S' | cut -c12-19`
VAR1=$(date -u --date="$a sec UTC" +%s)
VAR2=$(date -u --date="$f sec UTC" +%s)
DIFF2=$(( $VAR2 - $VAR1 ))
if [ $DIFF2 -lt 59 ]; then
echo "ok"
else
echo "nok"
fi

3 Answers 3

1

I guess that with if there is no log in logfile, you mean that the logfile either does not exist or is empty. You can do this in bash with

logfile=/var/log/nginx/error.log
[[ -f $logfile && -s $logfile ]] || exit 1

-f tests that it is a plain file, and -s tests that it is not empty.

Sign up to request clarification or add additional context in comments.

Comments

1

You can check fr the existence of a file using:

if [ ! -f '/var/log/ngnix/error.log' ]
then
  exit
fi

Comments

1

Just check if file doesn't exist or is empty and exit code

LOG_FILE="/var/log/nginx/error.log" [ ! -s $LOG_FILE -o ! -f $LOG_FILE ] && exit $?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.