问题
How could I append a cron task in crontab via a perl script?
I thought of the following:
#!/usr/bin/perl
use strict;
use warnings;
`crontab<<EOL
00 * * * * /home/slynux/download.sh
EOL`
I don't want to mess up things, so am I on the right track?
Also if I append it, how would I remove it? I am new in Perl
回答1:
Quick & dirty way :
#!/usr/bin/perl
use strict; use warnings;
`(crontab -l; echo "00 * * * * /home/slynux/download.sh") | crontab -`;
Another (better) approach :
#!/usr/bin/perl
use strict; use warnings;
open my $fh, "| crontab -" || die "can't open crontab: $!";
my $cron = qx(crontab -l);
print $fh "$cron\n0 * * * * /home/slynux/download.sh\n";
close $fh;
To remove the crontab
line(s) with /home/slynux/download.sh
:
#!/usr/bin/perl
use strict; use warnings;
open my $fh, "| crontab -" || die "can't open crontab: $!";
my $cron = qx(crontab -l);
$cron =~ s!.*/home/slynux/download\.sh.*!!g;
print $fh $cron;
close $fh;
回答2:
A quick search on metacpan returns Config::Crontab. While I have never used this module, it looks like it would do what you want.
来源:https://stackoverflow.com/questions/18133498/how-to-use-perl-to-modify-crontab