2017-03-07 65 views
-1

我知道這個問題相當微不足道,但仍然卡住了。 我已經使用過system(),exec()和back ticks,但是我的解決方案並不合適。 那麼我想要的是,我想從我的Perl腳本運行一個命令。如何在perl腳本中使用linux bash命令?在perl腳本中使用它出現錯誤

下面是一個例子: -

假設命令我想執行的

/scratch/abc/def/xyz/newfold/newfile.py --action=remove; 

check.txt: -

Installation root: /scratch/abc/def/xyz 

Install.pl:-

#!/usr/bin/perl 
use strict; 
use warnings; 
use Cwd; 
my $now=cwd; 
print "############################"; 
print "*****DELETING THE CURRENT SERVICE*****\n"; 
my $dir = $ENV{'PWD'}; 
#my $dir = /scratch/Desktop; 
my $inst=`grep -i 'Installation root' $dir/check.txt `; 
my $split=`echo "$inst" | awk '{print \$(3)}'`;   ## this will give the  "/scratch/abc/def/xyz" path 

#chdir ($split);   //Trying to change the directory so that pwd will become till xyz. 
qx(echo "cd $split"); 

$now=cwd; 
print $now; 
my $dele = `echo "$split/newfold/newfile.py --action=remove;"`;  //Problem is here it gets out from the $split directory and could not go inside and execute the command. 
print $dele; 

輸出預計爲: - 它應該進入目錄並執行子目錄命令。 請建議如何在不退出會話的情況下輕鬆執行命令行。

+0

'$ inst'包含行尾字符。 'chomp'它在你使用它來設置'$ split'之前。那麼你也需要'chomp $ split'。 – mob

回答

0

通過Perl執行的每個系統命令都會繼承程序的當前工作目錄(cwd)。 chdir()可以讓你把cwd改成不同的目錄,所以,繼承這個新的dir到執行的系統命令。

如果您不想更改腳本的cwd,一種簡單的方法是使用您想要執行的命令在連接(「;」)中使用「cd」來更改工作目錄。考慮到這一點,你可以嘗試這樣的事情:

#!/usr/bin/perl 
use strict; 
use warnings; 
use Cwd; 

my $cwd = getcwd(); 

print "CWD: $cwd\n"; 

print "############################"; 
print "*****DELETING THE CURRENT SERVICE*****\n"; 

unless (-e "$cwd/check.txt") { 
    print "-E-: File ($cwd/check.txt) not found in dir: $cwd\n"; 
    exit 0; 
} 

### Grep the /scratch/Desktop/check.txt, if the user launches 
### the script at /scratch/Desktop directory 
my $inst=`grep -i 'Installation root' $cwd/check.txt`; 

chomp($inst); 

### Regexp could be simpler to remove label 
$inst =~ s/.*root\:\s*//; 

print "Installation Root: $inst\n"; 

### Here the concatenation is used to chdir before the script execution 
### Changed to system() since you want to dump the outputs 

system("cd $inst; $inst/newfold/newfile.py --action=remove"); 

print "Done!\n";