重写这个问题以避免更多的反对票,因为对我来说删除它已经太晚了:
我正在编写一个脚本,要求用户确认之前sourcing
一些其他脚本。为了简化代码,假设有两个脚本sourced
,但我希望用户可以source
没有或仅是其中一个脚本 - 不是两者都存在。我试图使用以下形式的声明if true source-script else exit
这不起作用,因为我会退出if
语句,而且是整个脚本,并且没有机会进行必要的清理。最初,我的脚本看起来像这样:
echo "This script might do something terrible to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "terrible_script.sh"
# want some way to ensure that we don't prompt the user about the next script
# don't want to just exit if the response is 'n' because we have to do cleanup
fi
echo "This script might do something really good to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "good_script.sh"
fi
# do cleanup here
# regardless of whether or not any scripts were sourced
@charles-duffy 提供了答案 - 只需将提示包装在函数中即可。就像是:
function badscript() {
echo "This script might do something terrible to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "terrible_script.sh"
return 0
fi
}
function goodscript() {
echo "This script might do something really good to your computer."
read -p "Do you wish to continue? (y/[n]) " -n 1;
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
source "good_script.sh"
fi
}
if ! badscript
then
goodscript
fi
# cleanup code here
第一:不要做任何这样的事情。以其他方式构建你的程序。如果您向我们描述why如果您认为您需要这种行为,我们可能已经告诉您如何实现它。
解决这个问题:如果你将你的块包裹在一个循环中,你可以使用break
提前退出:
for _ in once; do
if true; then
echo "in the loop"
break
echo "not reached"
fi
done
echo "this is reached"
或者,您可以使用一个函数,并且return
提前退出:
myfunc() {
if true; then
echo "in the loop"
return
fi
echo "unreached"
}
myfunc
echo "this is reached"
或者,您可以将循环包装在子 shell 中(尽管这会阻止它执行其他操作,例如影响子 shell 外部代码的变量赋值):
(if true; then
echo "in the block"
exit
echo "unreached"
fi)
echo "this is reached."
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)