从 bash 脚本返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47176906/
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-18 16:34:58  来源:igfitidea点击:

return values from bash script

linuxbashechoreturn-value

提问by Bramat

I want to create a Bash file that returns a value. Meaning, in script script_a.bash I have a certain calculation, and script script_b.bash will call it.

我想创建一个返回值的 Bash 文件。意思是,在脚本 script_a.bash 中我有一定的计算,脚本 script_b.bash 会调用它。

script_a.bash:

script_a.bash:

return *5

script_b.bash:

script_b.bash:

a_value=./script_a.bash 3

when a_value will be 15.

当 a_value 为 15 时。

I read a little bit about that, and saw that there's no "return" in bash, but something like this can be done in functions using "echo". I don't want to use functions, I need a generic script to use in multiple places.

我读了一些关于它的内容,发现 bash 中没有“返回”,但是可以在使用“echo”的函数中完成类似的操作。我不想使用函数,我需要一个通用脚本在多个地方使用。

Is it possible to return a value from a different script? Thanks!

是否可以从不同的脚本返回值?谢谢!

回答by choroba

Use command substitution to capture the output of echo, and use arithmetic expression to count the result:

使用命令替换捕获 的输出echo,并使用算术表达式计算结果:

script_a.bash:

script_a.bash:

echo $((  * 5 ))

script_b.bash

script_b.bash

a_value=$( script_a.bash 3 )

回答by Tom Fenech

Don't use returnor exit, as they're for indicating the success/failure of a script, not the output.

不要使用returnor exit,因为它们用于指示脚本的成功/失败,而不是输出。

Write your script like this:

像这样写你的脚本:

#!/bin/bash

echo $((  * 5 ))

Access the value:

访问值:

a_value=$(./script_a.bash 3)

That is, use a $(command substitution)in the consuming code to capture the output of the script.

也就是说,$(command substitution)在消费代码中使用 a来捕获脚本的输出。

回答by dimirsen

You can use exit rc;, but keep in mind that conventionally in *nix 0 is a successful result, any positive value is an error code. Is it an option to call

您可以使用 exit rc;,但请记住,通常在 *nix 0 中是成功的结果,任何正值都是错误代码。是否可以选择调用

echo <your_value>;

and redirect output to the next binary called in the chain?

并将输出重定向到链中调用的下一个二进制文件?