如何调用shell脚本的子例程并将某些参数传递给它?像下面这样的东西?
#!/usr/bin/perl
### need something like this
source file.sh
routine; # <-- this is supposed to be part of file.sh which is called
# from perl script and some parameter are passed to it
答案 0 :(得分:1)
没有。它们是两种不同的语言。您所能做的就是从Perl调用shell脚本作为子进程,例如使用system()
或qx()
。
用一种语言编写程序,Perl或shell,不要试图混合它们。
好的,可能从shell导出一个函数,然后在Perl中解析并执行它,但这是很多工作,不安全,而且通常不值得付出努力。
答案 1 :(得分:0)
解决这个问题的方法是将例程的内容从file.sh中分离到subfile.sh中 - 然后你可以在Perl中执行此操作:
@cmdargs=('subfile.sh', $arg1, "arg2");
system(@cmdargs);
第一个列表元素是命令,第二个是Perl变量的值,作为参数传递给subfile.sh;第三个是作为参数传递给subfile.sh的文字。
通过在file.sh中编写subfile.sh的包装器来避免在subfile.sh和file.sh中的例程内容副本之间出现维护问题,并且只需使用适当的参数调用它,就像任何其他shell命令一样,无论你在哪里'在file.sh中调用例程。
我认为这样可行。