0

I have this command to review the last 10 min of the log:

perl -MDate::Parse -ne 'print if/^(.{15})\s/&&str2time($1)>time-600' /path/log

Now I want to put it in a script and put a variable instead of 600, to be able to modify the time more easily

#!/bin/bash
lasttime="600"
perl -MDate::Parse -ne 'print if/^(.{15})\s/&&str2time($1)>time-$lasttime' /path/log
# script does not end here. Run other commands like sed, grep etc. Why it should be in bash

But nothing comes out on the screen. But if I remove the variable it works fine

#!/bin/bash
perl -MDate::Parse -ne 'print if/^(.{15})\s/&&str2time($1)>time-600' /path/log

What should I modify so that it accepts the variable?

acgbox
  • 312
  • 2
  • 13
  • 1
    Why not just write a perl script then? – Gerhard Jul 14 '20 at 14:17
  • 1
    You are using single quotes they will not interpolate in Bash. But I would recommend using the `-s` option to pass a variable from Bash to perl, it is safer for injection attacks and you do not need to escape perl variables – Håkon Hægland Jul 14 '20 at 14:19
  • because it is a bash that has other commands – acgbox Jul 14 '20 at 14:20
  • 1
    Re "*You are using single quotes*", And keep it that way, Generating Perl code from a shell script is something you want to avoid! – ikegami Jul 14 '20 at 14:24
  • @ikegami : It is usually to avoid, but in this case, the only tainted part is `lasttime`, and the OP sets this variable explicitly, so if he wants to shoot himself into the foot, he has to do it knowingly. – user1934428 Jul 14 '20 at 14:31
  • 1
    @ajcg Try this: `perl -MDate::Parse -sne 'print if/^(.{15})\s/&&str2time($1)>time-$lasttime' -- -lasttime="$lasttime" -- /path/log` – Håkon Hægland Jul 14 '20 at 14:33
  • @user1934428, Nothing to do with tainting; it's just too friggen complicated. ok, it might be integer here --I doubt its guaranteed, but let's assume it is-- so you could save a couple of characters, but it'll cost readability. So still bad. – ikegami Jul 14 '20 at 14:37
  • @HåkonHægland Works!. Thanks. Please. Put the answer below to select it as correct – acgbox Jul 14 '20 at 14:39
  • He can't as this question was closed as a duplicate of one with an answer that gives the above solution and two others. – ikegami Jul 14 '20 at 14:40
  • Mmm. ok. So thanks again. It has been solved – acgbox Jul 14 '20 at 14:41
  • in this other way it also works into a bash: `perl -MDate::Parse -ne "print if/^(.{15})\s/&&str2time(\$1)>time-$lasttime" /path/log` – acgbox Jul 14 '20 at 15:23
  • 1
    @ajcg Did you read this thread: https://stackoverflow.com/q/53524699/1765658 (and maybe upvote;) ? – F. Hauri - Give Up GitHub Jul 16 '20 at 06:39
  • @F.Hauri. Yes, and I have given my upvote. thanks – acgbox Jul 16 '20 at 13:07

0 Answers0