Bash - 从下标返回值到父脚本

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

Bash - Return value from subscript to parent script

bash

提问by user1049697

I have two Bash scripts. The parent scripts calls the subscript to perform some actions and return a value. How can I return a value from the subscript to the parent script? Adding a returnin the subscript and catching the value in the parent did not work.

我有两个 Bash 脚本。父脚本调用下标来执行一些操作并返回一个值。如何将下标中的值返回给父脚本?在下return标中添加 a并在父级中捕获值不起作用。

回答by cdarke

I am assuming these scripts are running in two different processes, i.e. you are not "sourcing" one of them.

我假设这些脚本在两个不同的进程中运行,即您不是“采购”其中之一。

It depends on what you want to return. If you wish only to return an exit code between 0 and 255 then:

这取决于你想返回什么。如果您只想返回 0 到 255 之间的退出代码,则:

# Child (for example: 'child_script')
exit 42
# Parent
child_script
retn_code=$?

If you wish to return a text string, then you will have to do that through stdout (or a file). There are several ways of capturing that, the simplest is:

如果您希望返回文本字符串,则必须通过 stdout(或文件)来执行此操作。有几种捕获方法,最简单的是:

# Child (for example: 'child_script')
echo "some text value"
# Parent
retn_value=$(child_script)

回答by GoinOff

Here is another way to return a text value from a child script using a temporary file. Create a tmp file in the parent_script and pass it to the child_script. I prefer this way over parsing output from the script

这是使用临时文件从子脚本返回文本值的另一种方法。在 parent_script 中创建一个 tmp 文件并将其传递给 child_script。我更喜欢这种方式而不是解析脚本的输出

Parent

家长

#!/bin/bash
# parent_script
text_from_child_script=`/bin/mktemp`
child_script -l $text_from_child_script
value_from_child=`cat $text_from_child_script`
echo "Child value returned \"$value_from_child\""
rm -f $text_from_child_script
exit 0

Child

孩子

#!/bin/bash
# child_script
# process -l parm for tmp file

while getopts "l:" OPT
do
    case $OPT in
      l) answer_file="${OPTARG}"
         ;;
    esac
done

read -p "What is your name? " name

echo $name > $answer_file

exit 0

回答by Nagasaki

return a value from the subscript and check the variable $? which contain the return value

从下标返回一个值并检查变量 $? 其中包含返回值