bash 从另一个脚本中获取一个 shell 脚本并检查返回码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16669212/
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
source a shell script from another script and check return code
提问by amin
I want to source a file eg name.sh from another script and check the return code and decide on it's error code. If I use
我想从另一个脚本中获取一个文件,例如 name.sh 并检查返回代码并确定它的错误代码。如果我使用
source name.sh
then if name.sh return non-zero return code my main script stop to run but I need to decide on exit code weather to continue or stop.
然后,如果 name.sh 返回非零返回代码,我的主脚本将停止运行,但我需要决定退出代码天气是继续还是停止。
If I use
如果我使用
ret_code="`source name.sh`"
echo $ret_code
then ret_code is null and no error code is printed. I can't use these:
然后 ret_code 为空并且不打印错误代码。我不能使用这些:
sh name.sh
./name.sh
bash name.sh
because name.sh is not executable and I don't want it to be executable
因为 name.sh 是不可执行的,我不希望它是可执行的
采纳答案by Grzegorz ?ur
File does not need to be executable to run sh name.sh. Than use $?.
文件无需可执行即可运行sh name.sh。比用$?。
sh name.sh
ret_code=$?
回答by unxnut
The return code should be in the variable $?. You can do the following:
返回码应该在变量中$?。您可以执行以下操作:
source name.sh # Execute shell script
ret_code=$? # Capture return code
echo $ret_code
回答by Keith Hanlan
Amin, the return value of name.sh is simply the return value of the last command executed. Access it using $?as usual.
阿明,name.sh 的返回值只是上次执行命令的返回值。$?像往常一样访问它。
The simplest approach to capturing a return code is to structure "name.sh" so that failed commands result in no more commands being executed (which might succeed and then mask the error). Since you are using bash, you can also use functions. Just move your logic into a function and call it. This way, your name.shbecomes a one-liner and the value of $?will be whatever the function return.
捕获返回码的最简单方法是构造“name.sh”,以便失败的命令导致不再执行命令(这可能会成功,然后掩盖错误)。由于您使用的是 bash,因此您也可以使用函数。只需将您的逻辑移动到一个函数中并调用它。这样,您name.sh就变成了单行程序,并且$?无论函数返回什么,它的值都将是。
For example:
例如:
# cat fred
function f() {complicated; logic; here; export FRED="asdf";return 1;}
f
# source fred
# echo $?
1
# echo $FRED
asdf
However, if you put your logic into a function, then you might as well source the file and then call the function at your leisure.
但是,如果您将逻辑放入一个函数中,那么您不妨获取文件,然后在闲暇时调用该函数。
# cat fred
function f() {complicated; logic; here; export FRED="asdf";return 1;}
# source fred
# f && echo "that worked!" || echo "failed again"
failed again
# echo $FRED
asdf

