我知道在 bash
脚本(例如 here)中有几个关于 exit
与 return
的问题。
关于这个主题,但与现有问题不同,我相信,我想知道是否有关于如何从 bash
脚本安全地实现“提前返回”的“最佳实践”这样,如果用户获取脚本,则不会退出用户当前的 shell。
诸如 this 之类的答案似乎基于“exit
”,但如果脚本是源代码,即使用“.
”(点空格)前缀运行,则脚本在 current shell 的上下文,在这种情况下,exit
语句具有退出当前 shell 的效果。我认为这是一个不受欢迎的结果,因为脚本不知道它是在子 shell 中获取还是运行——如果是前者,用户可能会意外地让他的 shell 消失。如果调用者获取当前 shell,是否有提前返回的方法/最佳实践不退出当前 shell?
例如这个脚本...
#! /usr/bin/bash
# f.sh
func()
{
return 42
}
func
retVal=$?
if [ "${retVal}" -ne 0 ]; then
exit "${retVal}"
# return ${retVal} # Can't do this; I get a "./f.sh: line 13: return: can only `return' from a function or sourced script"
fi
echo "don't wanna reach here"
...如果它是从子 shell 运行的,则不会杀死我当前的 shell...
> ./f.sh
>
...但如果它是源代码,则杀死我当前的 shell:
> . ./f.sh
想到的一个想法是将代码嵌套在条件语句中,这样就没有显式的 exit
语句,但是我的 C
/C++
bias 认为提前返回在美学上比嵌套代码更可取。还有其他真正“早退”的解决方案吗?
最佳答案
在不导致父 shell 终止的情况下退出脚本的最常见解决方案是首先尝试 return
。如果失败则退出
。
您的代码将如下所示:
#! /usr/bin/bash
# f.sh
func()
{
return 42
}
func
retVal=$?
if [ "${retVal}" -ne 0 ]; then
return ${retVal} 2>/dev/null # this will attempt to return
exit "${retVal}" # this will get executed if the above failed.
fi
echo "don't wanna reach here"
你也可以使用return ${retVal} 2>/dev/null ||退出“${retVal}”
。
希望这对您有所帮助。
关于bash - 如何安全地提前退出 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012444/