简体   繁体   English

我们可以在perl脚本中创建bash实例吗?

[英]Can we create bash instance in perl script?

I am trying to use Perl to create a process running bash and then create a file sample.txt , but after the bash command I can't see any output on the console or any sample.txt file in the same directory structure. 我正在尝试使用Perl创建一个运行bash的进程,然后创建一个文件sample.txt ,但是在bash命令之后,我无法在同一目录结构中看到控制台上的任何输出或任何sample.txt文件。 Can somebody help me to fix following code? 有人可以帮我修复以下代码吗?

my $var = `bash -l`;
system($var);
print "Done!";

my $filename = 'sample.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
chmod(0777, "sample.txt");
print $fh "hello";
close $fh;
print "Done 1!..";

Bash's -l argument is convincing it to stay interactive. Bash的-l参数说服它保持交互性。 Running: 运行:

perl -e 'print `bash -l`'

On its own has the bash process bound to stdin interactively, but the subprocess's output is captured by perl and printed later when bash exits, which it will only do when you press Control D , issue exit or logout etc. bash进程本身具有交互式绑定到stdin的功能,但是perl会捕获子进程的输出,并在bash退出时稍后打印,只有在按Control D ,发出exitlogout等操作时,子进程的输出才会执行。

You probably wanted to start with $var = 'bash -l'; 您可能想以$var = 'bash -l'; . That will start bash interactively at first, and when you exit, will continue the remainder of the program. 这将首先以交互方式开始bash,并且当您退出时,将继续该程序的其余部分。 To me it's unusual to want to do this and I expect you should write something for bash that exits normally, probably with the -c argument. 对我来说,这是不寻常的做到这一点,我想你应该写的东西可以让bash是正常退出,可能与-c参数。

Replacing your first two lines of code with: 用以下代码替换前两行代码:

 system("bash", "-c", "echo Hello World!");

accomplishes this and the remainder of the program executes normally. 完成此操作后,程序的其余部分将正常执行。 I'm unsure what you wanted bash to do for you however. 但是我不确定您希望bash为您做什么。 These example cases would be better accomplished with just 仅用这些示例案例就可以更好地完成
system("echo", "Hello World!") or print "Hello World!" system("echo", "Hello World!")print "Hello World!" .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM