2015-05-29 3 views
2

Я работаю над этим в течение последних двух месяцев, и, несмотря на то, сколько раз я смотрю на него, я не могу заставить его работать. Этот скрипт проверяет ежедневные файлы журналов для пользовательской переменной, поэтому им не нужно просматривать все вручную. Он отлично справлялся с текущим месяцем, но если пользователь хочет проверить 20 дней, а сегодня 12-го числа этого месяца, я хотел бы иметь возможность вернуться к предыдущему месяцу (не искать файл журнала с дата 20150399 и т. д.). Я проверил логику вычислений на день/день, и они выглядят нормально (если есть лучший способ сделать это в BASH, я открыт для предложений). Что происходит, когда я пытаюсь отлаживать, это неожиданный конец файла. Я несколько новичок в написании сценариев, которые содержат более 20 строк, но я просто не могу придумать то, что мне не хватает. Я пробовал различные исправления, но безрезультатно, но я думаю, что это последняя итерация. Идеи?BASH-скрипт, проверяющий файлы журнала за текущий и предыдущий месяц

#!/bin/bash 
######################################################## 
# multi_log_chk.sh 
# This script will take input from the user and report which 
# CyberFusion MFT logs contain what the user is looking for. 
# Hopefully this will save the user having to search through every 
# stinking log file to find what they are looking for. 
# 20150406 pxg007 started typing 
# 20150413 pxg007 added && comparison for back out (line 28) 
#     added message for no entries found (line 32, 38, 48-52) 
#         Added some further description (line 16) 
# 20150424 pxg007 Added logic to calculate previous month and if necessary, year. (Lines 16-24, 60-78) 
# 
######################################################## 

currDate=`date +%d%B%C%y` 
currDay=`date +%d` 
currMnth=`date +%m` 
currYear=`date +%C%y` 
case $currMnth in                        #Let's establish number of days for previous month 
     05 | 07 | 10 | 12) lastMnthD=30;; 
     01 |02 | 04 | 06 | 09 | 08 | 11) lastMnthD=31;; 
     03) lastMnthD=28;;                    ##and screw leap year 
esac 
if [ $currMnth -eq 01 ]; then                 ##accounting for January 
     lastMnth=12 
     else 
     lastMnth=$((currMnth-1)) 
fi 
if [ $lastMnth -eq 12 ]; then               ## accounting for Dec of previous year 
     lastMnthYr=$((currYear-1)) 
     else 
     lastMnthYr=$currYear 
fi 


echo "This script will find entries for your query in whatever available MFT logs you request." 
echo " " 
echo "For instance - how many log files have transfer entries with \"DOG\" in them?" 
echo " " 
echo "I also will also give an estimate of how many transfers per log file contain your query, give or take a couple." 
echo " " 
echo "This search is case sensitive, so \"DOG\" is *** NOT *** the same as \"dog\"" 
echo " " 
read -p "What text you are looking for? Punctuation is okay, but no spaces please. " looking   ### what we want to find 
echo " " 
echo "Today's date is: $currDate." 
echo " " 
read -p "How many days back do you want to search(up to 25)? " daysBack     ### How far back we are going to look 
     if [ "$daysBack" == 0 ] && [ "$daysBack" >> 25 ]; then 
     echo "I said up to 25 days. We ain't got more than that!" 
     exit 1 
     fi 
echo " " 
echo "I am going to search through the last $daysBack days of log files for:\"$looking\" " 
echo " " 
read -p "Does this look right? Press N to quit, or any other key to continue: " affirm 
     if [ "$affirm" = N ] && [ "$affirm" = n ]; then ###Yes, anything other than "N" or "n" is a go 
     echo "Quitter!" 
     exit 1 
      else 
       nada=0           ### Used to test for finding anything 
       backDate=$((currDay-daysBack))     ### current month iterator (assuming query covers only current month) 
       if (("$daysBack" => "$currDay")); then     ## If there are more logs requested than days in the month... 
         lastMnthCnt=$((daysBack-currDay))        ### how many days to check last month 
         lastMnthStrt=$((lastMnthD-lastMnthCnt))     ## last month start and iterator 
         backDate=$(currDay-(daysBack-lastMnthCnt))    # Setting the iterator if we have to go back a month 

           while (("$lastMnthStrt" <= "$lastMnthD")); do 
           foundIt=$(grep "$looking" /CyberFusion/log/Log.txt."$lastMnthYr$lastMnth$lastMnthStrt" | parsecflog | wc -l) 
           howMany=$((foundIt/40+1))      ### Add one in case there are less than 40 lines in the record. 
             if (("$foundIt" > 0)) 
             then 
             nada=$((nada+1)) 
             echo "Log.txt.$lastMnthYr$lastMnth$lastMnthStrt contains $looking in approximately $howMany transfer records." 
             lastMnthStrt=$((lastMnthStrt+1)) 
             echo " " 
             else 
             lastMnthStrt=$((lastMnthStrt+1)) 
             fi 
       fi 
         backDate=$((currDay-daysBack))     ### current month iterator (assuming query covers only current month) 
           while (("$backDate" <= "$currDay")); do 
           foundIt=$(grep "$looking" /CyberFusion/log/Log.txt."$backDate" | parsecflog | wc -l) 
           howMany=$((foundIt/40+1))            ### Add one in case there are less than 40 lines in the record. 
             if (("$foundIt" > 0)) 
             then 
             nada=$((nada+1)) 
             echo "Log.txt.$backDate contains $looking in approximately $howMany transfer records." 
             backDate=$((backDate+1)) 
             echo " " 
             else 
             backDate=$((backDate+1)) 
             fi 


         if [ "$nada" \< 1 ] 
         then 
         echo " " 
         echo "I found no entries for $looking in any log file." 
         fi 
+4

вы когда-нибудь попробовать 'дата --date = "- 20 дней" +"% d% B% C% у "'? – leu

+0

Есть ли что-нибудь под этой первой линией 'echo', относящейся к вопросу здесь? Потому что, если это не так, вы должны удалить его из сообщения. –

+0

думаю. Я уверен, что проблема находится где-то в одном из операторов if или while. Я вложил все это только для того, чтобы лучше понять, что я был типичным для всего беспорядка. –

ответ

0

Вам не хватает ключевого слова «сделано» в строках 81 и 96, а также окончательное ключевое слово «fi» на последней строке.

Кроме того, как другие предложили вы можете сделать

date -d "20 days ago" +"%d%B%C%y" 

легко получить дату в прошлом

Смежные вопросы