Bash 循环(?)if语句
我是shell脚本编写的新手,我想知道:Bash 循环(?)if语句,bash,shell,unix,Bash,Shell,Unix,我是shell脚本编写的新手,我想知道: #!/usr/local/bin/bash number=5 echo "Enter 'yes' to continue, 'no' to abort:" read choice if [ $choice = yes ]; then while [ $number -lt 10 ]; do echo "The script is now looping!" done elif [ $choi
#!/usr/local/bin/bash
number=5
echo "Enter 'yes' to continue, 'no' to abort:"
read choice
if [ $choice = yes ]; then
while [ $number -lt 10 ]; do
echo "The script is now looping!"
done
elif [ $choice = no ]; then
echo "Loop aborted"
else
echo "Please say 'yes' or 'no'"
read choice
# What now?
fi
如果您没有指定“是”或“否”,我将如何进行if语句重新检查您的$choice(第13行)
多谢各位
您可以跟踪是否在名为
invalid\u choice的变量中循环
invalid_choice=true
while $invalid_choice; do
read choice
if [ "$choice" = "yes" ]; then
invalid_choice=false
...
elif [ "$choice" = "no" ]; then
invalid_choice=false
...
else
echo "Please say yes or no"
done
或者,如果需要经常这样做,可以将其概括为一个函数:
function confirm() {
local ACTION="$1"
read -p "$ACTION (y/n)? " -n 1 -r -t 10 REPLY
echo ""
case "$REPLY" in
y|Y ) return 0 ;;
* ) return 1 ;;
esac
}
confirm "Do something dangerous" || exit