从 bash 脚本获取 perl 脚本的输出并退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5681066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:48:09  来源:igfitidea点击:

get output of perl script from bash script and exit

perlbash

提问by user391986

From a bash script how can i execute a perl script get the output and exit if value is = 0? Also in the perl script how do i return the value, do i just return it or do i print it?

如果值 = 0,我如何从 bash 脚本执行 perl 脚本获取输出并退出?同样在 perl 脚本中,我如何返回值,我是直接返回它还是打印它?

回答by William Pursell

#!/bin/bash

perl-script args && exit

If you want to continue running, the return value is in $?

如果要继续运行,返回值在$?

Note that there is a distinction between the value returned by the perl script and the output of the script. To get the output of the script, use the $() operator:

请注意,perl 脚本返回的值和脚本的输出之间存在区别。要获取脚本的输出,请使用 $() 运算符:

#!/bin/bash
output=$(perl-script args)

echo The perl script returned $?
echo The output of the script was $output

回答by Rafe Kettler

To get a return code, use the exitfunction. Example:

要获取返回码,请使用该exit函数。例子:

Perl script:

Perl 脚本:

if ($success) {
    $return_value = 0;
} else {
    $return_value = 1;
}
exit($return_value);

Bash script:

bash脚本:

perl scriptname args > outfile && exit

That's assuming that you want to exit if the return value of the Perl script is 0 and you want so save the output of the Perl script in outfile. If the return value is not zero, it's stored in $?, you can save that value to a variable if you please.

这是假设您想在 Perl 脚本的返回值为 0 时退出,并且您希望将 Perl 脚本的输出保存在outfile. 如果返回值不为零,则将其存储在 中$?,如果愿意,您可以将该值保存到变量中。

回答by anubhava

Your perl script: foo.pl

你的 perl 脚本:foo.pl

#!/usr/bin/perl
# do something and then
exit 1;

And inside your bash script foo.sh:

在你的 bash 脚本 foo.sh 中:

#!/bin/bash
# do something and then call perl script
perl foo.pl

# check return value using $?
echo "perl script returned $?"