2017-03-07 109 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";