简体   繁体   中英

Log output from bash script into log file and stdout while running from perl

I have perl script

perl script (install.pl):

use strict; use warnings;
use Term::ANSIColor;
my $logfilename = "install.log";
open LOG,">$logfilename" or die "failed to open log file reason:$!";
sub logMsg
{
    my ($msg) = @_;
    my ($error) = $_[1];
    $msg .= "\n";
    print LOG $msg;
    if( $error ) { print color 'red' ;}
    {print $msg}
    if( $error ) { print color 'reset' ;}   
}
sub lampInstall
{
    logMsg("Installing apache2, php, and mysql db");
    # Install apache2 and mysql:
    my $cmdOutput = `./ubuntu-lamp-install.sh`;
    print LOG "$cmdOutput\n";
}
lampInstall();
close LOG;

bash script (ubuntu-lamp-install.sh)

#!/bin/bash
sudo apt-get update
sudo apt-get install ntp
sudo /etc/init.d/ntp start
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server mysql-server/root_password password test" | sudo debconf-set-selections
echo "mysql-server mysql-server/root_password_again password test" | sudo debconf-set-selections
sudo apt-get install -y apache2 php5 libapache2-mod-php5
sudo service apache2 restart
sudo a2enmod ssl

The issues is that , when install.pl is invoked, it waits for long time and does not give any output information of what is being installed.I need it to change the perl script to display the output information from bash script(better if instantaneous) as well as log the output to log file. The script is written by someone else , I have very little knowledge of perl scripting.

You could do something like

open my $cmdOutut, "-|", "./ubuntu-lamp-install.sh";
while (<$cmdOutput>) {
    print LOG "$_\n";
    print "$_\n";
}

in your lampInstall() .

This is the new lampInstall() :

sub lampInstall
{
    logMsg("Installing apache2, php, and mysql db");
    # Install apache2 and mysql:
    open my $cmdOutut, "-|", "./ubuntu-lamp-install.sh";
    while (<$cmdOutput>) {
        print LOG "$_\n";
        print "$_\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM