How to run a Linux bash commands in a PERL script ?

Updated on September 3, 2017

A system administrator needs to be writing a lot of scripts for monitoring and maintaining systems. During the scripting, sometimes you may need to refer few native bash commands in perl. Here i will be showing you how to call those native commands in perl scripts :

How to run Linux commands in perl
How to run Linux commands in perl

Step 1 : Create a subroutine which takes the command, runs and returns the output.

sub runcmd {
           local($cmd) = @_;
           alarm $timeout;
           $childkilled = 0;
           $childpid = open(CMD, "exec $cmd 2>&1 |");
           return "failed to run \"$cmd\"\n" if (!defined($childpid));
           local(@output) = ;
           local($output) = join("\n", @output);
           alarm 0;
           $output = $timeout_msg if ($childkilled);
           return $output;

Step 2 : Create an another subroutine to run actual command

#Get Date When script is started running
sub getDate() {
              $logout=$logout." Cron Started At :".$out."\n";

Step 3 : Call the subroutine as below:


Step 4 : Redirect the date output command to a file using the below command :

open (LOG, ">>/var/log/logfile") || die "can't open logfile\n";
print LOG "$logout\n";
close (LOG) || die;

Download the complete PERL script

Was this article helpful?

Related Articles

Leave a Comment