![](/img/trans.png)
[英]How can I call a function defined in a bash shell script from a C program
[英]How to call a function (defined in shell script) in a Perl script
我有两个脚本,即shell_script.sh
和perl_script.pl
。
shell_script.sh
:它有函数定义,当从Perl脚本调用时,它将以批处理模式在Linux上执行某些命令。
perl_script.pl
:它具有要实现的代码和逻辑,用于调用等。
shell_script.sh
文件的内容如下:
bash-4.2$ cat shell_script.sh
#!/bin/bash
# Function Definitions
func_1 ()
{
echo "function definition"
}
func_2 ()
{
echo "function definition"
}
perl_script.pl
文件的内容如下:
bash-4.2$ cat perl_script.pl
#!/usr/bin/perl
use Getopt::Long;
my $var1;
my $var1;
GetOptions("var1=s" => \$var1,
"var2=s" => \$var2,
"help|?" => \$help );
if ($help)
{
HelpMenu();
}
print " Can I call the func_1 (defined in shell script) with arguments here..?? (in this perl script)";
我怎样才能在perl脚本perl_script.pl
调用函数func_1()
(在shell_script.sh
中定义)?
要调用shell 函数 ,shell需要知道它的定义。 实现的一个方法是让壳第一source
,它定义该函数的文件。 然后,在不退出shell的情况下,调用该函数。 从Perl脚本,例如:
system 'bash', '-c', 'source shell_script.sh; func_1';
要使用bash
函数,您需要使用bash
。 所以在一个Perl脚本中,你将你置于反叛或system
,你在一个bash
过程中† 。 然后,在该过程中,您可以使用函数source
脚本,将它们带入的脚本以及执行它们
funcs.sh
#!/bin/bash
function f1 {
t1=$1
u1=$2
echo "f1: t1=$t1 u1=$u1"
}
function f2 {
t2=$1
u2=$2
echo "f2: t2=$t2 u2=$u2"
}
在Perl(单线)
perl -wE'
@r = qx(source funcs.sh; f1 a1 b1; f2 a2 b2);
print "got: $_" for @r
'
其中qx是反引号的运算符,但也许更清晰。 如果你需要从这些函数返回,我会使用反引号。 如果你的/bin/sh
没有链接到bash
†那么明确地调用bash
perl -wE'
@r = qx(/bin/bash -c "source funcs.sh; f1 a1 b1; f2 a2 b2");
print "got: $_" for @r
'
对数组的赋值将qx
放在列表上下文中,其中它返回作为行列表运行的STDOUT
。 这可用于将返回与不同函数分开,如果它们各自返回一行。 a1,b1
和a2,b2
是传递给f1
和f2
参数。
打印
got: f1: t1=a1 u1=b1 got: f2: t2=a2 u2=b2
这做出了一些(合理的)假设。
如果没有必要返回,但功能只需要做他们的事情,你可以使用
system('/bin/bash', '-c', 'source ... ')
†它确实是/bin/sh
,但通常会降级为bash
。 检查你的系统( /bin/sh
可能是另一个shell的链接)。 或者确保bash
运行命令
my @ret = qx( /bin/bash -c "source base.sh; f1 a1 b1; f2 a2 b2" );
有关此示例的说明,请参阅文本。
这个问题太过分了,但是Env::Modify
提供了一种在Perl中使shell函数可用的方法。 使用Env::Modify
,您可以导入shell函数一次,并在子序列system
调用中反复使用它们。
use Env::Modify qw(:bash system source qx);
# import the shell functions
system("source shell_script.sh ; export -f func_1 func_2");
# alternate: put "export -f func_1 func_2" at the end of shell_script.sh and call
source("shell_script.sh");
# use the shell functions
system("func_1");
$output = `func_2`;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.