linux - 如何在 perl 脚本中使用 linux bash 命令?在 perl 脚本中使用它时出现错误

标签 linux perl

我知道这个问题很微不足道,但我仍然被困住了。 我已经使用了 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/

相关文章:

linux - Bash shell 脚本。变量作为参数。无引号与双引号

linux - 如何从串口接收到的字符中获取奇偶校验位?

php - 为 *Nix 和 Windows 设置 PHP 包含路径的正确方法

perl - 我们在Perl中有自动冠军吗?

regex - 否定多个词

c++ - 无法获取文件的锁

linux - Shell:将变量插入命令中

perl - LWP::UserAgent 和 500 SSL 协商失败

linux - 想要根据同一文件中另一列中的值就地编辑文件(替换列值)

perl Net::LDAP::LDIF 从变量字符串中读取 ldif