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 :
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; close(CMD); $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() { local($command)="date"; local($out)=&runcmd($command); $logout=$logout." Cron Started At :".$out."\n"; }
Step 3 : Call the subroutine as below:
&getDate();
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;