我知道这个问题很微不足道,但我仍然被困住了。 我已经使用了 system()、exec() 和 backticks,但解决方案我没有得到正确的解决方案。 所以我真正想要的是,我想从我的 perl 脚本运行命令。
这是一个例子:-
假设我要执行的命令是
/scratch/abc/def/xyz/newfold/newfile.py --action=remove;
检查.txt:-
Installation root: /scratch/abc/def/xyz
安装.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;
预期输出是:- 它应该进入目录并执行子目录命令。 请建议我如何在不退出 session 的情况下轻松执行命令行操作。
最佳答案
通过 Perl 执行的每个系统命令都将继承程序的当前工作目录 (cwd)。 chdir() 将使您将 cwd 更改为不同的目录,因此,将这个新目录继承到执行的系统命令。
如果您不想更改脚本的 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";
关于linux - 如何在 perl 脚本中使用 linux bash 命令?在 perl 脚本中使用它时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42646441/