我知道这个问题非常简单,但我仍然被卡住了。 我已经使用了system(),exec()和back ticks但解决方案我没有得到正确的解决方案。 所以我想要的是,我想从我的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 :(得分: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";