bash 将值从子 shell 脚本返回到父脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12936197/
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
Returning a value from child shell script to a parent script
提问by Gopinagh.R
I am having two shell scripts, say script1.sh and script2.sh. I am calling script2.sh from script1.sh. In script2.sh a few evaluations are done and based the results a flag is being set. Now i need to pass the flag to script1.sh based on which it will be decided whether the script1.sh should continue it execution or exit. I am not using functions. and while i export the flag, in script1.sh it is blank.
My question now is how do i return the flag from script2.sh ?
Any help ? Any Ideas? Experiences to share?
我有两个 shell 脚本,比如 script1.sh 和 script2.sh。我正在从 script1.sh 调用 script2.sh。在 script2.sh 中完成了一些评估,并根据结果设置了一个标志。现在我需要将标志传递给 script1.sh,根据它决定 script1.sh 是继续执行还是退出。我没有使用函数。当我导出标志时,在 script1.sh 中它是空白的。
我现在的问题是如何从 script2.sh 返回标志?
有什么帮助吗?有任何想法吗?经验分享?
回答by Janito Vaqueiro Ferreira Filho
You could print the result and capture it in script1:
您可以打印结果并在 script1 中捕获它:
# Script 1
flag="$(./script2.bash)"
And:
和:
# Script 2
[...]
printf '%s\n' "$flag"
Hope this helps =)
希望这有帮助 =)
回答by Brian Agnew
I would expect you to use the return code from script2.sh(se by the statement exit {value})
我希望你使用script2.sh(se by the statement exit {value})的返回码
e.g.
例如
./script2.sh
$?contains the return value from script2.sh's exit statement.
$?包含script2.sh退出语句的返回值。
You can't use exporthere. exportmakes the variable available to subsequent subprocesses. It can't be used to communicate a value back to a parent process, since you're modifying a copy of the variable particular to the subprocess.
你不能export在这里使用。export使变量可用于后续子流程。它不能用于将值传递回父进程,因为您正在修改特定于子进程的变量的副本。
回答by choroba
Just use the exit status of script2:
只需使用 script2 的退出状态:
if script2.sh ; then
echo Exited with zero value
else
echo Exited with non zero
fi
Use exit 0or exit 1in script2 to set the flag.
在 script2 中使用exit 0或exit 1来设置标志。

