-1

I have a script that I am using to clear out all lines of a log files older than X days. X can be passed in via command line as well as the log file name, ex usage:

./purge-catalina.sh 3 /opt/tomcat8/logs/catalina.out

The script itself looks like this:

date_pattern=$(date -d "-$1 day" '+%Y-%m-%d')
catalina_file="$2"

echo "Purging all logs older than $date_pattern"
#grep -v "$pattern" $2 > catalina.out.temp; mv catalina.out.temp $2

awk -v d="$date_pattern" '($1 " " $2) > d' $catalina_file

When I pass in variables to the script and then run the awk command like above, the awk portion seems to not grab the correct lines. However, if I don't pass in any variables to the script and hardcode the variables to be:

date_pattern=$(date -d "-3 day" '+%Y-%m-%d')
catalina_file="logfile.log"

It works fine. How can I pass in variables to the script and also use $1 and $2 in the awk script?

  • 2
    Why not use logrotate? It won't fix your current problem, but it makes more sense going forward. – 84104 Apr 26 '18 at 17:26
  • @84104 I'm using this in conjunction with a logrotate script but it compresses the logs and moves them to a back-up daily. This log we use sometimes we have to go back a couple days to review issues, so I don't want to purge the data daily. – ninjasense Apr 26 '18 at 17:29
  • 1
    Try adding set -x at the beginning of the script, and see what's different between running it with arguments vs. hardcoded variables. If that doesn't point out the problem, please add enough info for someone else to duplicate the problem (e.g. a short sample log, what you expect it to print from that, and what it actually does print). – Gordon Davisson Apr 27 '18 at 2:11
1

Your script works as expected for me.

You should really execute using bash script.sh 3 /blah as that ensures you're actually using bash; you may find you're actually using dash or similar, though what you have written is correct sh.

$ ./script.sh 3 /opt/comca
Purging all logs older than 2018-04-24
awk -v d="2018-04-24" '($1 " " $2) > d' /opt/comca

$ cat script.sh
date_pattern=$(date -d "-$1 day" '+%Y-%m-%d')
catalina_file="$2"

echo "Purging all logs older than $date_pattern"
#grep -v "$pattern" $2 > catalina.out.temp; mv catalina.out.temp $2

echo "awk -v d=\"$date_pattern\" '(\$1 \" \" \$2) > d' $catalina_file"

Have you thought about something simpler?

sed -ne "/^$date_pattern/,\$p" "$catalina_file"

will output lines from the first occurrence of $date_pattern to the end. You may find debugging easier if that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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