重写这个问题以避免更多的downvotes,因为我删除它为时已晚:
我正在编写一个脚本,要求用户确认并在sourcing其他脚本之前.为了简化代码,想象一下可能有两个脚本sourced,但我希望用户可以是sourcenone或者只是其中一个脚本 - 而不是两者.我试图使用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
Run Code Online (Sandbox Code Playgroud)
@ 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
Run Code Online (Sandbox Code Playgroud)
第一:不要做这些.以其他方式构建您的程序.如果你向我们描述了为什么你认为你需要这种行为,我们可能会告诉你如何实现它.
回答这个问题:如果你把你的块包裹在一个循环中,你可以用来break提前退出:
for _ in once; do
if true; then
echo "in the loop"
break
echo "not reached"
fi
done
echo "this is reached"
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用函数,并return提前退出:
myfunc() {
if true; then
echo "in the loop"
return
fi
echo "unreached"
}
myfunc
echo "this is reached"
Run Code Online (Sandbox Code Playgroud)
或者,您可以将循环包装在子shell中(尽管这会阻止它执行其他操作,例如影响子shell外部代码的变量赋值):
(if true; then
echo "in the block"
exit
echo "unreached"
fi)
echo "this is reached."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16171 次 |
| 最近记录: |