2012-11-18 57 views
4

我是小白到shell脚本,我想知道这一点:循环if语句

#!/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语句重新检查$选择(第13行),如果你不要指定“是”或“否”?

谢谢。

回答

2
  1. 你可以把代码从“echo Enter ...”放到fi的外部“while”循环中。 while循环会循环直到$ choice为“yes”或“no”。这样做时删除最后一个“else”子句(这将是多余的)。

  2. P.S.您需要在内部while循环中增加(或更改)$数字。否则,它将无限运行。

+0

得到它的工作。谢谢! :) – Jordanss10

2

你可以在一个名为invalid_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