gpt4 book ai didi

bash - 如何在不退出程序的情况下退出bash中的if语句?

转载 作者:行者123 更新时间:2023-12-05 00:41:31 24 4
gpt4 key购买 nike

重写这个问题以避免更多的反对,因为我删除它为时已晚:

我正在编写一个脚本,在 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

最佳答案

首先:不要这样做。以其他方式构建您的程序。如果您向我们描述了为什么您认为您需要这种行为,我们可能会告诉您如何以其他方式实现它。


回到问题:如果您将 block 包装在一个循环中,您可以使用 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"

或者,您可以将循环包装在子外壳中(尽管这会阻止它执行其他操作,例如影响子外壳外部代码的变量赋值):

(if true; then
echo "in the block"
exit
echo "unreached"
fi)
echo "this is reached."

关于bash - 如何在不退出程序的情况下退出bash中的if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com