简体   繁体   English

在Perl中采购Shell脚本

[英]Sourcing shell scripts in Perl

I want to source a shell script from within Perl and have the environment variables be available in Perl, but I'm not sure if there's an elegant way to do it. 我想从Perl中获取shell脚本,并在Perl中使用环境变量,但是我不确定是否有一种优雅的方法。 Obviously, using system() won't work since it runs in a forked process, and all environment changes will be lost. 显然,使用system()无效,因为它在派生的进程中运行,并且所有环境更改都将丢失。 I think there's a CPAN module that can do it, but I prefer not to use external modules. 我认为有一个CPAN模块可以做到这一点,但我不希望使用外部模块。

I've seen two solutions that would not work in my case: 我已经看到了两种不适用于我的情况的解决方案:

  1. Have a wrapper that calls the shell script, and then calls the Perl script. 有一个包装程序,调用外壳程序脚本,然后调用Perl脚本。 I do not know ahead of time which of my shell scripts I need to call. 我不提前知道需要调用哪个Shell脚本。

  2. Manually opening the shell script and scraping for arg=value pairs. 手动打开shell脚本并抓取arg=value对。 This won't work either because the shell script is not a simple list of ARG=VALUE , but rather contain a bunch of conditionals, and variables can have different values depending on certain conditions. 这也不起作用,因为shell脚本不是ARG=VALUE的简单列表,而是包含一堆条件,并且变量可以根据特定条件具有不同的值。

sh -c "source script; env"应该在环境的末尾以name = value对的形式输出环境,然后您可以从您的perl脚本中进行解析(因为Perl是用于解析的语言,因此应该很容易)。

You can do this by installing external module from CPAN which is Shell::Source 您可以通过从CPAN安装Shell :: Source的外部模块来完成此操作

$env_path= Shell::Source->new(shell=>"tcsh",file=>"../path/to/file/temp.csh");
$env_path->inherit;

As perl creates its own instance while running on a shell, so we can not set environment path for the main shell as the perl's instance will be like sub shell of the main shell. 由于perl在外壳程序上运行时会创建自己的实例,因此我们无法为主外壳程序设置环境路径,因为perl的实例将类似于主外壳程序的子外壳程序。 Child can not set environment paths for parents. 儿童无法为父母设置环境路径。

Now till the perl's sub shell will run you'll be able to access all the paths present in temp.csh by using Shell::Source 现在,在perl的子shell运行之前,您将可以使用Shell :: Source访问temp.csh中存在的所有路径。

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

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