gpt4 book ai didi

linux - 打破 Bash 中的嵌套函数循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:51 28 4
gpt4 key购买 nike

我正在使用嵌套函数来分区并为连接到新 Linux 机器的驱动器制作文件系统。我在尝试打破所有循环时遇到一个奇怪的问题。

我正在跟踪嵌套循环索引并使用“break n”。当用户对“Do you have any additional drives to partition?”的问题回答“n”时我希望跳出所有嵌套循环并继续执行脚本,但结果是问题再次被问到。

你能帮我解决这个问题吗?

INIT_STARTED=0
chooseDisks()
{
INIT_STARTED=$((INIT_STARTED+1))
# Choosing which drive to work on
read -p "Please type the name of the disk you want to partition: " DISK

while true; do
read -p "Are you sure you want to continue ? y (partition)/n (choose another drive) /x (continue) " ynx
case $ynx in
[Yy]* )
containsElement "$DISK"
if [ $? == 1 ]; then
initializeDisk $DISK

# remove element from found disk to prevent trying to partition it again.
delete=($DISK)
FOUNDDISKS=( "${FOUNDDISKS[@]/$delete}" )
else
echo "${red}$DISK is not a valid choice, please select a valid disk.${reset}"
chooseDisks
fi

break;;
[Nn]* )
chooseDisks
break $((INIT_STARTED));;
[Xx]* )
return
break;;
* ) echo "Please answer y or n. x to continue the script.";;
esac
done

# Any additional disks to partition?
while true; do
read -p "Do you have any additional drives to partition ? y/n " yn
case $yn in
[Yy]* )
#chooseDisks $FOUNDDISKS
chooseDisks
break $((INIT_STARTED));;
[Nn]* )
return
break $((INIT_STARTED));;
* ) echo "Please answer y or n";;
esac
done

}

我希望这样:

break $((INIT_STARTED));;

结束第n次循环并退出函数。

最佳答案

不要玩嵌套逻辑 break,只需使用一些变量,如 $userStop 而不是 while true;做

userStop = false
while[!${userStop}]
do
#...
# replace break $((INIT_STARTED));; by
# userStop = true

关于linux - 打破 Bash 中的嵌套函数循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56114632/

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