为避免更多的否决,我重写了这个问题,因为现在已经太晚删除它:
我正在编写一个脚本,询问用户是否确认并在 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
return
可以在if语句
内部使用。 - smac89